Updated: Mon, 6-15-20 @11:45pm b4 midnite
         Tue, 6-09-20,   Fri, 5-29-20,   Thu, 5-28-20 @10:45pm     // Note: Tue, 6-9-20 2:08am; started at past midnite
         Tue, 05-26-20  Mon, 05-25-20   Sat, 04-16-20   Wed, 02-12-20

 

--cut space line
line1
line2

 

>> add to network notes >> adding userss and domain thru DosCmds  >>  1337red.wordpress.com/building-and-attacking-an-active-directory-lab-with-powershell/

 

Java Pgming Notes:

Format:

a Programs Hello World
 
 
 
Java
 
1
2
3
4
5
6
7
public class MyClass {
   public static void main(String[] args) {
      System.out.println("Hello World!");
   }
}

 

 

  ** Online Java compiler; Good to test your java pgm;      - note enable interactive to put in your entries
https://www.jdoodle.com/online-java-compiler/ 

 

    Html Editor for everyone
https://www.qhmit.com/html/online-html-editor/full/

 

 

  Good authors / teachers / video for java pgming
-Caleb
-Awaiz Mirza
-Mike Dane
-Eli Computer guy (Network, DNS, Active Directory, etc)
-
-java sample mini pgms
-
-

 

  ** java mini sample codes

https://projectsgeek.com/2014/07/link-handler-system-project-in-java.html#comment-224098

 

  Essential to learn the syntax

-input and output console 
-integer, double and string
-increment  i++, or i=+  and i--, 
-if, while, case 
-Numeric Methods (max, compare, valueOf, parseInt, etc)
- string Class (string.format, length) 
- String Methods (charAt, concat, contains, indexOf, lastIndexOf)
- More String Methods (toLowerCase, strip, substring, repeat, equals) 
- Creating Basic Classes, Methods, and Properties 
-
-
-
 

*** Start Sample of java pgms ** ------------------------

 

----- t2.java pgm -------  first pgm to read datafile ; this is working one! on Tue, 6-9-20 -----------

// your 1st pgm to read file with CSV ; ran on Tue, 6-9-20
  import java.io.*;  
  import java.util.Scanner;  
  public class t2    // note: you need to name this same as your java name pgm
{  
  public static void main(String[] args) throws Exception  
     {  

// parsing a CSV file into Scanner class constructor  
     Scanner sc = new Scanner(new File("d:\\CSVDemo.csv"));   // specify your file Fname.csv; note double \\ before FileName
     sc.useDelimiter(",");                                    //sets the delimiter pattern  

// do while loop to read each line
     while (sc.hasNext())                                     //returns a boolean value  
       {  
       System.out.print(sc.next());        //find and returns the next complete token from this scanner  
       }   
     sc.close();                           //closes the scanner  
     }  


// ** end of your java pgm

 

---- CSVDemo.csv datafile; put csv as extension;  ------------
Shashank, Mishra, Auditor, 909090090, 45000, Moti Vihar
Naveen, Singh, Accountant, 213344455, 12000, Shastri Nagar
Mahesh, Nigam, Sr. Manager, 787878878, 30000, Ashok Nagar
Manish, Gupta, Manager, 999988765, 20000, Saket Nagar


--------- how to run your 1st Reading a file java pgm ----------
1. download java compiler from oracle
2. change path
3. test run with simple pgm >> hello world
4. Done!  ready to run other pgms!

----

After installing your Java from oracle site, you are ready to 
run java; however, make sure you change info of your path!  
1. Go to Advanced settings
2. Variables
3. edit path
4. add >> C:\Program Files\Java\jdk-12.0.1\bin;

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jdk-12.0.1\bin

5. save it, OK
6. exit DosCmd
7. re run DosCmd
8. check path, type path to ensure path is now included where your javac pgm is!

---- Running your java pgm
1. Must have your java t2.pgm (see above)
2. Must have your datFile.csv


**Go to Dos and run your java t2.java pgm
1. javac youpgm.java    (dont forget to put extension java!)
2. when it finished, it would create yourPgm dot class
3. run yourPgm,

dos>> java youPgm  (note, no extension!!  see below)


**Result:

D:\>javac t2.java

D:\>java t2
Shashank Mishra Auditor 909090090 45000 Moti Vihar
Naveen Singh Accountant 213344455 12000 Shastri Nagar
Mahesh Nigam Sr. Manager 787878878 30000 Ashok Nagar
Manish Gupta Manager 999988765 20000 Saket Nagar

D:\>

** fin!! t2.java pgm **

------ another reader pgm >> t3.java --------

 

// reader pgm

import java.io.File;                             // Import the File class
import java.io.FileNotFoundException;            // Import this class to handle errors
import java.util.Scanner;                        // Import the Scanner class to read text files

public class t3 {                                // call your t3 read pgm
  public static void main(String[] args) {
    try {
      File myObj = new File("d:\\TEMP3.txt");    // put your file name here! ; note double \\
      Scanner myReader = new Scanner(myObj);
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();       // read each line
        System.out.println(data);                // display each line 
      }
      myReader.close();
    } catch (FileNotFoundException e) {          // use exception if File not found!!
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

// end of reader pgm; working one.   It will read txt file and output whatever in it. 

 

 

-----------------

Ssmple9:  reading file

Create a File

To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):

Example

import java.io.File;  // Import the File class
import java.io.IOException;  // Import the IOException class to handle errors

public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      if (myObj.createNewFile()) {
        System.out.println("File created: " + myObj.getName());
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

 

The output will be:

File created: filename.txt

======

 

Write To a File

In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:

Example

import java.io.FileWriter;   // Import the FileWriter class
import java.io.IOException;  // Import the IOException class to handle errors

public class WriteToFile {
  public static void main(String[] args) {
    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

The output will be:

Successfully wrote to the file.
Run example »

 

 

 

import java.io.File;  // Import the File class
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      Scanner myReader = new Scanner(myObj);
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        System.out.println(data);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

 

To get more information about a file, use any of the File methods:

Example

import java.io.File;  // Import the File class

public class GetFileInfo { 
  public static void main(String[] args) {
    File myObj = new File("filename.txt");
    if (myObj.exists()) {
      System.out.println("File name: " + myObj.getName());
      System.out.println("Absolute path: " + myObj.getAbsolutePath());
      System.out.println("Writeable: " + myObj.canWrite());
      System.out.println("Readable " + myObj.canRead());
      System.out.println("File size in bytes " + myObj.length());
    } else {
      System.out.println("The file does not exist.");
    }
  }
}

The output will be:

File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0

 

 

 

======

 

 

sample8:  String format() method

Example of Java String format() method

note that %s, for string, %.6f for number with decimals

%s – for strings
%f – for floats
%d – for integers

 

public class Example{  
   public static void main(String args[]){  
	String str = "just a string";  
		
	//concatenating string using format
	String formattedString = String.format("My String is %s", str);  
		
	/*formatting the  value passed and concatenating at the same time
	 * %.6f is for having 6 digits in the fractional part
	 */
	String formattedString2 = String.format("My String is %.6f",12.121);

	System.out.println(formattedString); 
	System.out.println(formattedString2);  
   }
}

Output:

My String is just a string
My String is 12.121000

--------

 

sample 8a:  Format method

 

public class JavaExample {  
   public static void main(String[] args) {  
	String str1 = String.format("%d", 15); // Integer value  
	String str2 = String.format("%s", "BeginnersBook.com"); // String  
	String str3 = String.format("%f", 16.10); // Float value  
	String str4 = String.format("%x", 189);  // Hexadecimal value  
	String str5 = String.format("%c", 'P');  // Char value  
	String str6 = String.format("%o", 189); // Octal value
	System.out.println(str1);  
	System.out.println(str2);  
	System.out.println(str3);  
	System.out.println(str4);  
	System.out.println(str5);  
	System.out.println(str6); 
   }  
}

Output:
15
BeginnersBook.com
16.10000
bd
P
275

 

Java String Format Specifiers

%c – Character
%d – Integer
%s – String
%o – Octal
%x – Hexadecimal
%f – Floating number
%h – hash code of a value

-----

 

Sample7:  >> Array, Loop, var declaration for Int and String

Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand.

Let’s take the same example that we have written above and rewrite it using enhanced for loop.

class ForLoopExample3 {
   public static void main(String args[]){
      int arr[]={2,11,45,9};
      for (int num : arr) {
         System.out.println(num);
      }
   }
}

Output:

2
11
45
9

Note: In the above example, I have declared the num as int in the enhanced for loop. This will change depending on the data type of array. For example, the enhanced for loop for string type would look like this:

String arr[]={"hi","hello","bye"};
for (String str : arr) {
         System.out.println(str);
}

 

-----

sample2a:  loop using increments

 

Simple For loop

class ForLoopExample {
    public static void main(String args[]){
         for(int i=5; i>1; i--){
              System.out.println("The value of i is: "+i);
         }
    }
}

The output of this program is:


The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2

----

sample6: 

StringIndexOutOfBound Exception

Class: Java.lang.StringIndexOutOfBoundsException

E.g.

class ExceptionDemo4
{
   public static void main(String args[])
   {
      try{
	 String str="beginnersbook";
	 System.out.println(str.length());;
	 char c = str.charAt(0);
	 c = str.charAt(40);
	 System.out.println(c);
      }catch(StringIndexOutOfBoundsException e){
	  System.out.println("StringIndexOutOfBoundsException!!");
       }
   }
}

Output:

13
StringIndexOutOfBoundsException!!

-----------------

sample7:  exception catching

-discussion in >> https://stackoverflow.com/questions/39849984/what-is-a-numberformatexception-and-how-can-i-fix-it

soltn:

try {
    i = Integer.parseInt(myString);
} catch (NumberFormatException e) {
    e.printStackTrace();
    //somehow workout the issue with an improper input. It's up to your business logic.
}

to issue with the other code: it gotten some errors

 

Error Message:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace of Clubs"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at set07102.Cards.main(Cards.java:68)
C:\Users\qasim\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

---

My While Loop:

while (response != 'q' && index < 52) {
    System.out.println(cards[index]);
    int first_value = Integer.parseInt(cards[index]);
    int value = 0;
    //Add a Scanner
    Scanner scanner = new Scanner(System.in);
    System.out.println("Will the next card be higher or lower?, press q if you want to quit");
    String guess = scanner.nextLine();
    if(cards[index].startsWith("Ace")) { value = 1; }
    if(cards[index].startsWith("2")) { value = 2; }
    if(cards[index].startsWith("3")) { value = 3; }
    //checking 4-10
    if(cards[index].startsWith("Queen")){ value = 11; }
    if(cards[index].startsWith("King")){ value = 12; }
    if(guess.startsWith("h")){
        if(value > first_value){ System.out.println("You answer was right, weldone!"); } 
        else { System.out.println("You answer was wrong, try again!"); }
    } else if(guess.startsWith("l")){
        if(value < first_value) { System.out.println("You answer as right, try again!"); }
        else { System.out.println("You answer was wrong, try again!"); }
    } else { System.

 

** end ** ----------------- fin ---------------------