battle programmers alliance
Would you like to react to this message? Create an account in a few clicks or log in to continue.

battle programmers allianceLog in

the LivinGrimoire Artificial General Intelligence software design pattern forum

descriptionjava eclipse oxygen grimoire Emptyjava eclipse oxygen grimoire

more_horiz
1 install JDK (java developer kit)
install eclipse from eclipse.org choose the java developers install option

check your java version : https://www.youtube.com/watch?v=UokTaTwckDw

also C:\Users\Lenovo\eclipse-workspace
the eclipse folder created by the installer is where your project files get stored

2 when eclipse fires up choose new java project or from file, new, java, java project.


right click the project name in the solution explorer, new, to add packages to contain your classes or to
create a class. when you choose a class make sure to camel case its name and without spaces. also, check
static main void to define it as the main class.

package naming convention : com.companyName.projectName

2.2 to change class name :
right click class on the solution explorer, refactor, rename

2.3 comment in out selected code lines : ctrl + /
3 hello world code :

Code:


package PL;

public class test2 {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 System.out.println("hello world");
 }

}

ctrl + f11 to run code
4 making the intelliJ intellisense more sensitive : tool strip, window, preferences , java, editor, content assistent,
auto activation trigger, add abcdefghijklmnopqrstuvwxwz and in upper case and @_ to .

5 var declaration :
int x = 5;

double d1 = 2.5;
int y = (Int)d1; // explicit conversion
byte b1 = 12;
int b2 = b1; // implicit conversion

6 operators
xor operator 5>4 ^ 4==4 //false

7 randomizer :
math.random(); // returns double 0 to 1

8 get user input :
import java.util.Scanner; // at start of code

Scanner s1 = new Scanner(System.in); // after typing this intelliJ should add the import code anyways
int x = s1.nextInt(); // .next(); to input a string

9 shortcut if conditional :
string m1 = (3>1 ? "it is true":"it is false");

10 string jutsus :
compare :
str1.equals(str4);
string old style declare :
str5 = new String("moti rulz");
str.toLowerCase();// you know what it returns

string megazord :

Code:


package PL;

import java.util.Scanner;
import static java.lang.System.out;

public class test2 {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 String s1 = String.format("hi %s %s welcome %d", "king","moti",5);
 System.out.println(s1);
 
 }
}

prints :
hi king moti welcome 5

see string format java list for more data types (%s %d)

11 system.nanoTime();

12 loop beef ups:
break; // exits loop while its running
continue; // exit next lines of code in the loop and continue loops execusion

13 arrays :
int[] arr1 = {2,3,4}; // initialize array
System.out.println(Arrays.toString(arr1)); // print array

or

int arr2[]= {1,2,45};
System.out.println(Arrays.toString(arr2)); // full array print for 1D arrays

refer to organ in the array :
// array[x];
int[] arr1 = {2,3,4}; // initialize array
System.out.println(arr1[0]); // prints 2

or

int[] arr1 = {2,3,4}; // initialize array
arr1 = new int[2]; // recreate array you can also : int[] a1 = new int[size integer]
System.out.println(arr1[1]); // prints 0

int[][] g = new int[2][5]; // 2D array
g[1][3] = 5; // access organ
System.out.println(g[0].length); // get inner array size

shallow copy : ar2 = ar1; // changes to either array effect other array

deep copy array :
array2 = Arrays.copyOf(array1,array1.length);

sort array :
Arrays.sort(arr); // sorts arr, no need to return value it is sent by reference (shallow copy)

14 IDE jutsus :

intelliJ : when you type the editor will offer to auto complete code lines, choose code line and enter.

14.2 enable step into and variable watch debug option : click stripe to the left of the code line numbers to
insert a break point, click spider on tool strip next to run code button. right click close to close.

15 methodes :

Code:


package t3;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;

public class ttGood {
 static String var1 = "hadouken";
 public static void main(String[] args) {
 // TODO Auto-generated method stub
 printMe(); // STATIC FUNCTION CAN ONLY USE static functions
 printMe("moti");
 hadouken();
 hadouken(); // prints : hadouken!!
 System.out.println(futsujutsu(3,4)); // prints 7
 int[] a2 = {1,2,3,4};
 System.out.println(sumArray(a2)); //prints 10
 System.out.println(sumArray2(a2));
 System.out.println(sumArray2(1,2,3,4,5)); // prints 15
 }
 public static void printMe() {System.out.println(("rulz"));} // sub returns nothing
 public static void printMe(String name) {{System.out.println((name + " rulz"));}}
 public static void hadouken() {
 var1+="!";
 System.out.println((var1));}
 public static int futsujutsu(int x,int y) {return x+y;} // shared function
 public static int sumArray(int[] a1) {
 int sum=0; // for each loop called for int in java :
 for (int h:a1) {
 sum+=h;
 
 }
 return sum;
 } // shared function
 public static int sumArray2(int...nums) // treat array of variables as an object = var args
 {
 int sum=0; // for each loop called for int in java :
 for (int h:nums) {
 sum+=h;
 
 }
 return sum;
 } // shared function
 public static int[] dec(int[] a3) // array returning function
 {
 int[] newArray = Arrays.copyOf(a3, a3.length);
 for (int i = 0; i < newArray.length; i++) {
 newArray[i]+=1;
 }
 return newArray;
 }

}

16 string jutsus :
String sX = "hello";
char c1 = sX.charAt(2); // refer to string as array

char[] arr = sX.toCharArray(); // also refer to string as array

17 create and use object classes, examplified with the deck class that uses the card class
when adding those classes do not check the public static void main option which you check for the Main class:



card class :
[/code]
package gambit;

public class Card {
String type, color;
int level;
public void printCard() {

switch (level) {
case 1:System.out.println("Ace of " + type);break;
case 11:System.out.println("prince of " + type);break;
case 12:System.out.println("queen of " + type);break;
case 13:System.out.println("king of " + type);break;
default:System.out.println(color + " " + type + " level " + level);break;
}
}
}
[/code]
deck class :

Code:


package gambit;

public class Deck {
 Card[] cards = new Card[52];
 public void initDeck() {
 for (int i = 0; i < 13; i++) {
 cards[i] = new Card();
 cards[i].type = "clubs";
 cards[i].color = "black";
 cards[i].level = i+1;
 }
 for (int i = 13; i < 26; i++) {
 cards[i] = new Card();
 cards[i].type = "hearts";
 cards[i].color = "red";
 cards[i].level = i-12;
 }
 for (int i = 26; i < 39; i++) {
 cards[i] = new Card();
 cards[i].type = "spades";
 cards[i].color = "black";
 cards[i].level = i-25;
 }
 for (int i = 39; i < 52; i++) {
 cards[i] = new Card();
 cards[i].type = "diamonds";
 cards[i].color = "red";
 cards[i].level = i-38;
 }
 }
 public void printDeck() {
 for (int i = 0; i < 52; i++) {
 cards[i].printCard();
 }
 
 }
}

Main class :

Code:


package gambit;

public class Main {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 Deck d1 = new Deck();
 d1.initDeck();
 d1.printDeck();
 }

}

18 reseting the solution explorer window :
from the tool strip : window,show view, package explorer

19 class with constructor getter and setter (morse code example)
using getters and setters to access private(an acess modifier) class organs helps prevent code injections


type shift + alt + s to auto generate a constructor, getters and or setters, accourding to your
customization.

Code:

Code:


package morseCodePackage;

public class morseCode {
   private String user; // click on var and type alt + shift + s then select generate getters setters
   public String getUser() {
      return user;
   }
   public void setUser(String user) {
      this.user = user;
   }
   private static String lastMsg;
   public morseCode(String user) {this.user = user;} // I'm a constructor, use this. if the param names are
   // the same as the classes
   public String toMorse(String msg) {lastMsg = code(msg);return this.user + " " + this.lastMsg;}
   public String toHuman(String msg) {return this.user + " " + decoder(msg);}
   public static String code(String msg) {
      char[] arr = msg.toCharArray();
      String result ="";
      for (int i = 0; i < arr.length; i++) {
        
         result += charToMorse(arr[i]);
      }
      return result;
   }
   private static String charToMorse(char x) {
      String result="";
      switch (x) {
      case 'a': result = "*-";break;
      case 'b': result = "-***";break;
      case 'c': result = "-*-*";break;
      case 'd': result = "-**";break;
      case 'e': result = "*";break;
      case 'f': result = "**-*";break;
      case 'g': result = "--*";break;
      case 'h': result = "****";break;
      case 'i': result = "**";break;
      case 'j': result = "*---";break;
      case 'k': result = "-*-";break;
      case 'l': result = "*-**";break;
      case 'm': result = "--";break;
      case 'n': result = "-*";break;
      case 'o': result = "---";break;
      case 'p': result = "*--*";break;
      case 'q': result = "--*-";break;
      case 'r': result = "*-*";break;
      case 's': result = "***";break;
      case 't': result = "-";break;
      case 'u': result = "**-";break;
      case 'v': result = "***-";break;
      case 'w': result = "*--";break;
      case 'x': result = "-**-";break;
      case 'y': result = "-*--";break;
      case 'z': result = "--**";break;
      case '0': result = "-----";break;
      case '1': result = "*----";break;
      case '2': result = "**---";break;
      case '3': result = "***--";break;
      case '4': result = "****-";break;
      case '5': result = "*****";break;
      case '6': result = "-****";break;
      case '7': result = "--***";break;
      case '8': result = "---**";break;
      case '9': result = "----*";break;
      case '.': result = "*-*-*-";break;
      case ',': result = "--**--";break;
      case '?': result = "**--**";break;
      case ' ': result = "/";break;
      
      default:
         break;
      }
      return result + "/";
   }
   public static String decoder(String msg) {
      
      String morseChr ="";
      String result = "";
      char[] arr = msg.toCharArray();
      for (int i = 0; i < arr.length; i++) {
         if(arr[i]!='/') {morseChr += arr[i];}
         else {result += morseCharToChar(morseChr);morseChr="";}
      }
      result = result.replaceAll("  ", " ");
      return result;
   }
   private static char morseCharToChar(String x) {
      char result='@';
      switch (x) {
      case "*-": result = 'a';break;
      case "-***": result = 'b';break;
      case "-*-*": result = 'c';break;
      case "-**": result = 'd';break;
      case "*": result = 'e';break;
      case "**-*": result ='f' ;break;
      case "--*": result = 'g';break;
      case "****": result = 'h';break;
      case "**": result = 'i';break;
      case "*---": result = 'j';break;
      case "-*-": result = 'k';break;
      case "*-**": result = 'l';break;
      case "--": result = 'm';break;
      case "-*": result = 'n';break;
      case "---": result = 'o';break;
      case "*--*": result = 'p';break;
      case "--*-": result = 'q';break;
      case "*-*": result = 'r';break;
      case "***": result = 's';break;
      case "-": result = 't';break;
      case "**-": result = 'u';break;
      case "***-": result = 'v';break;
      case "*--": result = 'w';break;
      case "-**-": result = 'x';break;
      case "-*--": result = 'y';break;
      case "--**": result = 'z';break;
      case "-----": result = '0';break;
      case "*----": result = '1';break;
      case "**---": result = '2';break;
      case "***--": result = '3';break;
      case "****-": result = '4';break;
      case "*****": result = '5';break;
      case "-****": result = '6';break;
      case "--***": result = '7';break;
      case "---**": result = '8';break;
      case "----*": result = '9';break;
      case "*-*-*-": result = '.';break;
      case "--**--": result =',' ;break;
      case "**--**": result = '?';break;
      case "/": result = ' ';break;
      
      default:
         break;
      }
      if(result == '@') {result = ' ';}
      return result;
   }
   public static void describeME() {System.out.println("I'm a class that can code and decode morse code");}
}

main :
Code:

Code:


package morseCodePackage;

public class Main {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      System.out.println(morseCode.code("hadouken"));
      System.out.println(morseCode.code("over 9000"));
      String n1 = morseCode.code("hadouken");
      System.out.println(morseCode.decoder(n1));
      morseCode mc1 = new morseCode("moti");
      System.out.println(mc1.toMorse("souryuken"));
      System.out.println(mc1.toHuman("****/*-/-**/---/**-/-*-/*/-*/"));
      morseCode.describeME();
   }

}


20 exit the debug view :
debug, java browsing, next to the debug spider picture at the top right of the screen, there is a little square that says java
when you mouse hover it.

21 using a class from a different package :
import packageName;

import import packageName.*; // import all files
import packageName.className;

22 const variable :
final double PI = 3.141;

declaring a methode as final makes it unoverridable.

23 enum : declare a group of string const to access via intelliJ :
rightClick package name, enum :

Code:


package pokemon;

public enum Day {
 SUN,MON,TUE,WED,THU,FRI,SAT
}

Main :

Code:


public class Main {
 public static void dayOfWeek(Day d) {
 switch(d) {
 
 case SUN:System.out.println("sunday");break;
 }
 
 }
 public static void main(String[] args) {
 dayOfWeek(Day.SUN);
 Day[] d1 = Day.values(); // create a days array
 System.out.println(Arrays.toString(d1));
 System.out.println(Day.FRI.ordinal());
 System.out.println(d1[Day.SUN.ordinal()+3]);
 }

}

24 classes and inheritance :

base class (super class):

Code:


package pokemon;

public class PokEgg {
 private String name;
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public PokEgg(String name) {
 // TODO Auto-generated constructor stub
 this.name = name;
 }
}

sub class (with an example for overidding toString methode):

Code:


package pokemon;

import java.awt.Window.Type;
import java.util.function.ToDoubleBiFunction;

public class Pokemon extends PokEgg {
 private String cry;
 private int level;
 public String getCry() {
 return cry;
 }
 public void setCry(String cry) {
 this.cry = cry;
 }
 public int getLevel() {
 return level;
 }
 public void setLevel(int level) {
 this.level = level;
 }
 
 public Pokemon(String name, String cry, int level) {
 // TODO Auto-generated constructor stub
 super(name);
 this.cry = cry;
 this.level = level;
 }
 /**
 * type slash astrics astrics to enable documentation
 */
 public String toString() {return super.getName() + "\n level : " + this.level +
 " says:  "
 + "" + this.cry;
 }
 
}

Main class :

Code:


package pokemon;

public class Main {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 Pokemon pickachu = new Pokemon("lars","pickach yu", 5);
 System.out.println(pickachu.toString());
 }

}

25 singleton is a object that can be created only x amount of times, usually once.
used for objects like server connection and rare game objects.

singleton class :
Code:

Code:


package singleton;

public class Singleton {
   private static Singleton singleton; // array this to get x number of singletons enabled
   private Singleton() {
      System.out.println("new singleton instace has been created");
   }
   public static Singleton newInstance() {
      if(singleton == null) {
         singleton = new Singleton();
      }
      return singleton;
   }
}


summoning the singleton object :

Code:

Code:


package singleton;

public class Main {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Singleton sing1 = Singleton.newInstance(); // can only create 1, all others point to the same object
      
      
   }

}


26 polymorphism is the creation of a controller, the base class, that is used to
utilize the methodes of its various Derived sub classes (objects).
polymorphism, exampled via the shape class, and its overridden surface area methode,
in the Main class.

shape super class :
Code:

Code:


package com.shapes.objects;

public class Shape {
  
   public Shape() {
      // TODO Auto-generated constructor stub
   }
   public double surfaceArea() {
      return 0;
   }
}


square sub class of shape

Code:

Code:


package com.shapes.objects;

public class Square extends Shape {
   private double height;

   public double getHeight() {
      return height;
   }

   public void setHeight(double height) {
      this.height = height;
   }
   public Square(double height) {
      this.height = height;
   }
   public double surfaceArea() {
      return height*height;
   }
}


rectangle sub class of square
Code:

Code:


package com.shapes.objects;

public class Rectangle extends Square{
   private double width;

   public double getWidth() {
      return width;
   }

   public void setWidth(double width) {
      this.width = width;
   }

   public Rectangle(double height, double width) {
      super(height);
      this.width = width;
   }
   @Override
   public double surfaceArea() {
      return super.getHeight()*width;
   }
  

}


triangle sub class of shape

Code:

Code:


package com.shapes.objects;

public class Triangle extends Shape {
   private double height;
   private double width;
  
   public Triangle(double height, double width) {
      super();
      this.height = height;
      this.width = width;
   }
   public double getHeight() {
      return height;
   }
   public void setHeight(double height) {
      this.height = height;
   }
   public double getWidth() {
      return width;
   }
   public void setWidth(double width) {
      this.width = width;
   }
   @Override
   public double surfaceArea() {
      return (height*width)/2;
   }
  
}


circle class extends (sub class of) shape super class:
Code:

Code:


package com.shapes.objects;

public class Circle extends Shape {
   private double Radius;
   public double getRadius() {
      return Radius;
   }
   public void setRadius(double radius) {
      Radius = radius;
   }
  
   public Circle(double radius) {
      super();
      Radius = radius;
   }
   public double surfaceArea() {
      return Radius*Radius*3.1415;
   }
}


main class plays around with the classes using polymorphism to refer to all objects as a shape
and using the override methods of the sub classes even though they were declared as the super class :

Code:

Code:


package com.shapes.objects;

import java.util.Scanner;

import org.w3c.dom.css.Rect;

public class Main {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Shape sh1 = new Shape();
      System.out.println(sh1.surfaceArea());
      Rectangle rec1 = new Rectangle(10, 5);
      System.out.println(rec1.surfaceArea());
      Shape sh2 = rec1;
      System.out.println(sh2.surfaceArea());
      
      Shape[] shapeArray = new Shape[5];
      
      for (int i = 0; i < shapeArray.length; i++) {
         System.out.println("enter shape");
         Scanner scanner2 = new Scanner(System.in);
         String x2 = scanner2.next();
         shapeArray[i] = getShape(x2);
         System.out.println(shapeArray[i].surfaceArea());
      }
   }
   public static Shape getShape(String form) {
      Shape result = null;
      Scanner scanner11 = new Scanner(System.in);
      switch (form) {
      case "square":
         System.out.println("enter square side size");
         double x1 = scanner11.nextDouble();
         return new Square(x1);
      case "circle":
         System.out.println("enter circle radius");
         double Radius1 = scanner11.nextDouble();
         return new Circle(Radius1);
      case "rectangle":
         System.out.println("enter rectangle height");
         double height = scanner11.nextDouble();
         System.out.println("enter rectangle width");
         double width = scanner11.nextDouble();
         return new Rectangle(height, width);
      case "triangle":
         System.out.println("enter triangle height");
         double Theight = scanner11.nextDouble();
         System.out.println("enter triangle width");
         double Twidth = scanner11.nextDouble();
         return new Triangle(Theight, Twidth);
      default:
         break;
      }
      return result;
   }

}

27 get original declared class name (sub class even if it was polymorphism declared into a base class object):
objectName.getClass().toString();

28 the object super class : all objects inherit from it.
class java.lang.objects. to override a super class methode from the derived class, type the methode name
and it will auto comlete. tyoe to, to auto complete the toString override.
the object class also have the object.finalize() methode to end a variable you finished using, though java does this
automatically.

get object class name :
c1.getClass().toString().substring(6); // c1 = object name.

protected methode : clone(), returns object
boolean : equals()
int : hashCode() // returns hash code value for the object.

30 brute force counter :

Code:


String arr[] = {"0","a","b","c"};
 String result = "";
 for (int i = 0; i < arr.length; i++) {
 for (int j = 0; j < arr.length; j++) {
 for (int j2 = 0; j2 < arr.length; j2++) {
 result += arr[i] + arr[j] + arr[j2] + " \n";
 }
 }
 }
 System.out.println(result);


31 generic lv1 :

Code:


package gener;

public class myGeneric {
 public static <T> void Print(T[] input) {
 for (T t: input){
 System.out.println(t);
 }
 }

}

main :

Code:


package gener;

public class main {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 String arr[] = {"0","a","b","c"};
 myGeneric.Print(arr);
 }

}

lv2 :
a generic class :

Code:


package gener;

public class myGeneric<T> {
 Object[] myType = new Object[0];
 public void add(T value) {
 Object[] temp = new Object[myType.length+1];
 for (int i = 0; i < temp.length - 1; i++) {
 temp[i]= (T)myType[i];
 }
 temp[temp.length -1]= value;
 myType = new Object[temp.length];
 for (int i = 0; i < temp.length; i++) {
 myType[i] = (T)temp[i];
 }
 }
 public void printArray() {
 for (int i = 0; i < myType.length; i++) {
 System.out.println((T)myType[i]);
 }
 }
 public static <T> void Print(T[] input) {
 for (T t: input){
 System.out.println(t);
 }
 }
 public T getElement(int index) {return (T)myType[index];}
 @Override
 public String toString() {
 String result ="";
 for (int i = 0; i < myType.length; i++) {
 result+=(T)myType[i] + " \n";
 }
 return result;
 }
 public int indexOf(T element) {
 int result = -1;
 for (int i = 0; i < myType.length; i++) {
 if((T)myType[i]==element) {return i;}
 }
 return result;
 }

}

main :

Code:


package gener;

public class main {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 String arr[] = {"0","a","b","c"};
 myGeneric.Print(arr);
 myGeneric<String> x = new myGeneric<String>(); // Integer for int
 x.add("1");
 x.add("2");
 x.printArray();
 System.out.println(x.getElement(1));
 System.out.println("toString: " + x.toString());
 System.out.println("index of 1 is :" + x.indexOf("1"));
 }

}

32 abstract class :
an abs class doesn't have to have a constructor.

Code:
public abstract class AbsShape {
  public abstract int Area();
}

2nd class :
Code:

Code:


import java.util.regex.Matcher;

public class Square extends AbsShape{
   private int side;
  
   public int getSide() {
      return side;
   }

   public void setSide(int side) {
      this.side = side;
   }

   public Square(int side) {
      super();
      this.side = side;
   }

   @Override
   public int Area() {
      // TODO Auto-generated method stub
      return (int)Math.pow(side, 2); // powe ^
   }

}


Code:
public class Main {

  public static void main(String[] args) {
     // TODO Auto-generated method stub
     AbsShape ribua = new Square(5);
     System.out.println("area: " + ribua.Area());
  }

}

example 2 :
an abstract class doesn't have to have a constructor.

Code:

Code:


public abstract class BaseClass {
   protected int x = 100; // visible to this base class and sub classes(that extend it)
   protected int y = 150;
  
   public int getX() {
      return x;
   }

   public void setX(int x) {
      this.x = x;
   }

   public int getY() {
      return y;
   }

   public void setY(int y) {
      this.y = y;
   }

   public abstract void AbstractMethode();
  
}


derived class :
Code:
public class DerivedClass extends BaseClass{
 
  @Override
  public void AbstractMethode() {this.x++;this.y++;}
}

main :
Code:
public class Main {

  public static void main(String[] args) {
     BaseClass patamon = new DerivedClass();
     patamon.AbstractMethode();
     System.out.println(patamon.getX() + " " + patamon.getY());
  }

}

output : 101 151

33 interface :
an interface is like an item an object class can be equiped with.
interface contains methode signatures that has to be implemented in your object class.

right click the project folder in the package explorer window, interface.

Code:
public interface MyCalc {
  public int Add(int x, int y);
  public int subtract(int x, int y);
  public int Multiple(int x, int y);
  public int div(int x, int y);
}


2nd interface :

Code:
public interface MyCalc2 {
  public int Multiple(int x, int y);
  public int sum(int ... sigma);
}

create a class and add implements MyCalc,MyCalc2.
next click the error line under the class name and click add unimplemented methods.
finnally fill in the methodes body.
to get :

Code:

Code:


public class MainClass implements MyCalc,MyCalc2 {

   @Override
   public int sum(int... sigma) {
      // TODO Auto-generated method stub
      int result = 0;
      for (int i = 0; i < sigma.length; i++) {
         result += sigma[i];
      }
      return result;
   }

   @Override
   public int Add(int x, int y) {
      // TODO Auto-generated method stub
      return x+y;
   }

   @Override
   public int subtract(int x, int y) {
      // TODO Auto-generated method stub
      return x-y;
   }

   @Override
   public int Multiple(int x, int y) {
      // TODO Auto-generated method stub
      return x*y;
   }

   @Override
   public int div(int x, int y) {
      // TODO Auto-generated method stub
      return x/y;
   }

}


and creat some main class to test MainClass

34 java class with learnability :
written by moti barski

main :
Code:

Code:


import java.util.Arrays;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class Main {

 public static void main(String[] args) {
 boolean[] parts = {true,true,true,false};
 Car x = new Suzuki(parts);
 FixerBot fb1 = new FixerBot();

 fb1.gainExp(x);
 fb1.gainExp(new Suzuki(parts));
 fb1.gainExp(new Suzuki(parts));
 
 fb1.getRepairProphesy(new Suzuki(parts));
 
 
 }

}

car class :
Code:

Code:


import java.awt.Point;
import java.util.Arrays;
import java.util.Random;

public class Car {
 public boolean parts[] = new boolean[4];
 // steer, spoke, tire, wheel

 public Car(boolean[] parts) {
 super();
 this.parts = Arrays.copyOf(parts, parts.length);
 effects();
 }
 private void effects() {
 if(!parts[3]) {parts[2]=false;parts[1] = false;}
 }
 public void fixWithEffects(int part) {
 parts[part] = true;
 if(part == 3) {parts[2]=true;parts[1] = true;}
 }
 public int repairSuggestion() {
 int counter = 0;
 for (int i = 0; i < parts.length; i++) {
 if(!parts[i]) {counter++;}
 }
 int counter2 = 0;
 int brokenParts[] = new int[counter];
 for (int i = 0; i < parts.length; i++) {
 if(!parts[i]) {brokenParts[counter2]=i;counter2++;}
 
 }
 Random rn = new Random();
 int answer = rn.nextInt(counter);
 return brokenParts[answer];
 }
 public boolean working() {
 for (int i = 0; i < parts.length; i++) {
 if(!parts[i]) {return false;}
 }
 return true;
 }
 public String getState() {
 String result = "";
 for (int i = 0; i < parts.length; i++) {
 result += parts[i] + "";
 }
 return result;
 }
 
}

Suzuki car class, inherits from car class :
Code:
import java.awt.Point;
import java.sql.Ref;

public class Suzuki extends Car {
 private String name;
 
 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public Suzuki(boolean[] parts) {
 super(parts);
 // TODO Auto-generated constructor stub
 }
 
 
}

algorithm class :
Code:

Code:


import java.awt.Point;
import java.util.Arrays;

public class AlgMatrix {
 public String[][] states= new String[10][10];
 //public String[][] actions= new String[10][10];
 public void defaulter() {
 for (int i = 0; i < states.length; i++) {
 for (int j = 0; j < states[0].length -1; j++) {
 states[i][j] = "";
 
 }
 
 }
 for (int i = 0; i < states.length; i++) {
 states[i][9] = "xxxxxxxxxxxxxxxxxxxx";
 }
 }
 public Point StateLocate(String str) {
 Point tP = new Point(1000, 1000);
 int sl = states.length;
 String str2="";
 for (int i = 0; i < sl; i++) {
 for (int j = 0; j < sl-1; j++) {
 str2 = states[i][j];
 if(str2 != null) {if(str2.contains(str)) {tP.x = i;tP.y= j;break;}}
 
 }
 }
 return tP;
 }
 public void sortMe() {
 
 }
}

fixer bot class :
Code:

Code:


import java.awt.Point;
import java.awt.image.ReplicateScaleFilter;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Dictionary;
import java.util.Hashtable;

import org.omg.CORBA.PUBLIC_MEMBER;

public class FixerBot {
 public int expBarrier = 100;
 public AlgMatrix aMatrix = new AlgMatrix();
 Dictionary dic1 = new Hashtable();
 private String carKey(Car c1) {
 String Key = c1.getClass().toString().substring(6);
 
 for (int i = 0; i < c1.parts.length; i++) {
 Key += c1.parts[i] + "";
 }
 if(dic1.get(Key)==null) {aMatrix.defaulter();dic1.put(Key, aMatrix);}
 return Key;
 }
 public String repairCar(Car c1) {
 String Key = carKey(c1);
 //if too costly alg, gainExp
 //repair action + print
 
 aMatrix = (AlgMatrix)dic1.get(Key);
 
 return Key;
 }
 public void getRepairProphesy(Car c1) {
 String Key = carKey(c1);
 aMatrix = (AlgMatrix)dic1.get(Key);
 for (int i = 0; i < aMatrix.states.length; i++) {
 if(aMatrix.states[0][i]!=null) {System.out.print(aMatrix.states[0][i] +" ");}
 
 }
 }
 public void gainExp(Car c1) {
 if(!(c1.working())) {gainExpInner(c1);}
 else {System.out.println("car works");}
 }
 public void gainExpInner(Car c1) {
 
 String[] sc = new String[10];
 sc[0] = carKey(c1);
 AlgMatrix ax = (AlgMatrix)dic1.get(sc[0]);
 int sCount = 1;
 int cost =0;boolean b1;
 int nextFix;
 boolean b3 =  !(c1.working());
 boolean b2;
 Point tP1 = new Point(1000,1000);// change to 1;
 do {
 nextFix = c1.repairSuggestion();
 c1.fixWithEffects(nextFix);
 sc[sCount] = c1.getState() + "@" + nextFix;
 sCount++;cost++;this.expBarrier--;
 //AlgMatrix ax = (AlgMatrix)dic1.get(sc[0]);
 tP1 = new Point(ax.StateLocate(c1.getState()));
 b3 =  !(c1.working());
 b2 =  tP1.x < 1000;
 } while ((expBarrier == 0 && b2)|| b3);
 
 if(expBarrier == 0 && b2) {
 for (int i = tP1.y; i < sc.length; i++) {
 sc[i] = ax.states[tP1.x][i];
 cost++;
 }
 
 }
 for (int i = 0; i < sc.length; i++) {
 ax.states[sc.length -1][i] = sc[i];
 }
 String costStr ="";
 for (int i = 0; i < cost; i++) {
 costStr+="x";
 }
 ax.states[ax.states.length - 1][ax.states.length - 1] = costStr;
 //ax.sortMe();
 int min = 0;
 int minIndex = 0;
 String temp = "";
 for (int i = 0; i < ax.states.length; i++) {
 min = ax.states[i][ax.states.length-1].length();
 minIndex = i;
 for (int j = i+1; j < ax.states.length; j++) {
 if(ax.states[j][ax.states.length-1].length() < min) {minIndex =j;}
 }
 for (int j = 0; j < ax.states.length; j++) {
 if(i!=minIndex) {
 temp = ax.states[i][j];
 ax.states[i][j] = ax.states[minIndex][j];
 ax.states[minIndex][j] = temp;}
 }
 }
 dic1.put(sc[0], ax);
 }
}


about the output :
Suzukitruefalsefalsefalse truetruetruetrue@3 x  =
car + car state of parts @ part number to repair, amount of repairs = amount of x

35 generics level1 :

Code:


package gener;

public class myGeneric<T> {
 Object[] myType = new Object[0];
 public void add(T value) {
 Object[] temp = new Object[myType.length+1];
 for (int i = 0; i < temp.length - 1; i++) {
 temp[i]= (T)myType[i];
 }
 temp[temp.length -1]= value;
 myType = new Object[temp.length];
 for (int i = 0; i < temp.length; i++) {
 myType[i] = (T)temp[i];
 }
 }
 public void printArray() {
 for (int i = 0; i < myType.length; i++) {
 System.out.println((T)myType[i]);
 }
 }
 public static <T> void Print(T[] input) {
 for (T t: input){
 System.out.println(t);
 }
 }
 public T getElement(int index) {return (T)myType[index];}
 @Override
 public String toString() {
 String result ="";
 for (int i = 0; i < myType.length; i++) {
 result+=(T)myType[i] + " \n";
 }
 return result;
 }
 public int indexOf(T element) {
 int result = -1;
 for (int i = 0; i < myType.length; i++) {
 if((T)myType[i]==element) {return i;}
 }
 return result;
 }

}


main :

Code:


package gener;

public class main {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 String arr[] = {"0","a","b","c"};
 myGeneric.Print(arr);
 myGeneric<String> x = new myGeneric<String>();
 x.add("1");
 x.add("2");
 x.printArray();
 System.out.println(x.getElement(1));
 System.out.println("toString: " + x.toString());
 System.out.println("index of 1 is :" + x.indexOf("1"));
 }

}

descriptionjava eclipse oxygen grimoire Emptylist

more_horiz

Code:

package ok;


import java.util.ArrayList;
import java.util.Collections;

public class Main1 {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 ArrayList<Object> x = new ArrayList<>();
 x.add(1);
 x.add(4);
 x.add(9);
 Collections.shuffle(x);

 System.out.println(x.toString());
 
 }

}

fixing the The type List is not generic; it cannot be parameterized with arguments <String> error
and properly summoning a list in JAVA eclipse :

Code:

import java.util.ArrayList;
import java.util.List;

public class Main {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      List<String> x = new ArrayList<>();
      
   }

}


with shuffle. :face: :cherry:

descriptionjava eclipse oxygen grimoire Emptyjava dictionary s

more_horiz
dictionarys :
hashtable :

Code:

import java.util.Hashtable;

public class Main {

 public static void main(String[] args) {
 // sync methode, code waits for it to finish what it was told to do
 Hashtable<String, String> hashtable = new Hashtable<>();
 hashtable.put("moti","rulz");
 System.out.println(hashtable.get("moti"));
 }

}

treemap :

Code:

import java.util.TreeMap;

public class Main {

 public static void main(String[] args) {
 // sync methode, code waits for it to finish what it was told to do
 // faster if your tree has under 600 elements
 // tree <key, object>
 TreeMap<String,Integer> tMap = new TreeMap<>();
 tMap.put("moti", 100);
 tMap.put("chi", 4);System.out.println(tMap.values());
 System.out.println(tMap.keySet());
 
 }

}

hashMap:

Code:

import java.util.HashMap;

public class Main {

 public static void main(String[] args) {
 // async methode, coderuns in parallal and returns null if not finished B4 element called
 // to avoid err
 HashMap<String, String> hm1 = new HashMap<>();
 hm1.put("moti", "battle programmer");
 hm1.put("moti1", "battle programmer");
 System.out.println(hm1.get("moti"));//output :battle programmer
 System.out.println(hm1.keySet());//[moti, moti1]
 
 
 }

}

hashset list :

Code:


import java.util.HashMap;
import java.util.HashSet;

public class Main {

public static void main(String[] args) {
// does not allow an elemnts to re accure
HashSet<String> hs1 = new HashSet<>();
hs1.add("moti");
hs1.add("barski");
hs1.add("moti");
hs1.add("rulz");
System.out.println(hs1);//[moti, rulz, barski]
}

}
iterator :

Code:

import java.util.HashSet;
import java.util.Iterator;

public class Main {

 public static void main(String[] args) {
 // does not allow an elemnts to re accure
 HashSet<String> hs1 = new HashSet<>();
 hs1.add("moti");
 hs1.add("barski");
 hs1.add("moti");
 hs1.add("rulz");
 System.out.println(hs1);//[moti, rulz, barski]
 Iterator<String> it1 = hs1.iterator();
 while(it1.hasNext()) {System.out.println(it1.next());}//moti
 //rulz
 //barski
 }

}

descriptionjava eclipse oxygen grimoire Emptystrings and regex

more_horiz

Code:

String str1 = " hello world moti   rulz!!!";
 String[] strArr = str1.split(" "); // populates with words as array elements
 System.out.println(strArr[6]); // output = rulz!!!
 StringBuffer strBuff = new StringBuffer(str1.length()); // sync jutsu string buffer
 // string concation is more efficient with string buffer if it is 3 or more strings.
 for (int i = 0; i < strArr.length; i++) {
 strBuff.append(strArr[i] + " ");
 }
 System.out.println(strBuff);
 strBuff.insert(2,  "%");
 System.out.println(strBuff);
 strBuff.delete(2, 3);
 System.out.println(strBuff);
 System.out.println(strBuff.reverse());// reverses the string
 System.out.println(strBuff);// changes remain to the string buffer (it is still reversed here)
 String x = strBuff.toString();
 System.out.println(x);
 int a = Integer.parseInt("1234 ".trim());// convert string to integer
 boolean b = Boolean.parseBoolean("true");
 StringBuffer strBuff2 = new StringBuffer();
 strBuff2.append(a);strBuff2.append(" ");strBuff2.append(b);
 System.out.println(strBuff2);


REGEX : regular expressions
refer to next main code below

[search characters] : example : [A-za-z] [0-9]
[anti search characters] : [^A-z] [^0-9]
\\s : white space
\\S : not white space
\\d : any number
\\D : any char white isn't a number
{length min, length max} : {n,m}. {n,} will have only a minimum
{element occured x times} : {5}

[A-Za-z]{2,20} = \\w{2,20}  : search for any word 2 to 20 chars

regexChecker(your regex spell, the string you want to extract regexes from);

code exmples :
regexChecker("\\w{2,20}", longString); // search for any word 2 to 20 chars in long string

regexChecker("\\s\\d{5}\\s", longString); // search for 5 digit (zip code)

regexChecker("I[Lmno]|X[UV]", longString); // 2 chars that (begin with I than L or m or n or o)
// or (begin with X than U or V) country code basically

regexChecker("(\\{{1,})", strangeString); // search for words with at least 1 '{' char
regexChecker("(\\{+)", strangeString); // search for words with '{' char with something after it

regexChecker("[A-Za-z0-9._\\%-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}", longString);
/*
* search for an email :
* anychar + @ char followed by anychar + period followed by 2 to 4 char (.com .whateva)
*/

regexChecker("([0-9]( |-)?)?(\\(?[0-9]{3}\\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})", longString);
/*
* phone number regex above
* ([0-9]( |-)?)? :
* ()? = you don't know if the ex in the brackets will exist
* (\\(? search for that but it doesn't have to exist
* [0-9]{3} than 3 digits followed by \\)? that doesn't have to exist
*
*
*/

regexChecker("(?<=\\s|^)[Aa]\\S+[Bb]\\b", longString);
// all words starting with a ending with b (case of char irrelavent)

pattern : "(\\w+)(?= before me)"; gets word prev "before me"

GPS regex :

Code:

RegexUtil regexUtil = new RegexUtil();
      String pripyatLat = regexUtil.regexChecker(
            "([1-8]?[1-9]|[1-9]0)\\.{1}\\d{1,7}",
            " 50.4410852,30.4831796");
      System.out.println(pripyatLat);
      String pripyatLong = " 50.4410852,30.4831796".replace(pripyatLat + ",", "").trim();
      System.out.println(pripyatLong);



main code :
main class :

Code:

import java.util.regex.*;


public class Main {

 public static void main(String[] args) {
 
 String longString = " Moti Barski IL 12345 (123)666-6666 motimoti@fudgemail.net 666-555-1234 666 555-1234 ";
 String strangeString = " 1Z bbb **** *** {{{ {{ { ";
 //regexChecker("\\w{2,20}", longString);
 }
 public static void regexChecker(String theRegex, String str2Check){  
         // You define your regular expression (REGEX) using Pattern
         Pattern checkRegex = Pattern.compile(theRegex);
         // Creates a Matcher object that searches the String for
         // anything that matches the REGEX
         Matcher regexMatcher = checkRegex.matcher( str2Check );
         // Cycle through the positive matches and print them to screen
         // Make sure string isn't empty and trim off any whitespace
         while ( regexMatcher.find() ){
             if (regexMatcher.group().length() != 0){
                 System.out.println( regexMatcher.group().trim() );                  
                 // You can get the starting and ending indexs                  
                 System.out.println( "Start Index: " + regexMatcher.start());
                 System.out.println( "Start Index: " + regexMatcher.end());
             }
         }
         System.out.println();
     }
 public static void regexReplace(String str2Replace){
         // REGEX that matches 1 or more white space
         Pattern replace = Pattern.compile("\\s+");
         // This doesn't really apply, but this is how you ignore case
         // Pattern replace = Pattern.compile("\\s+", Pattern.CASE_INSENSITIVE);
         // trim the string t prepare it for a replace
         Matcher regexMatcher = replace.matcher(str2Replace.trim());
         // replaceAll replaces all white space with commas
         System.out.println(regexMatcher.replaceAll(", ")); // replace pattern regex
 // in str2Replace with ", "
     }

 }


alphabetic string compare
the following code gets the earlier string. reverse result<0 to result>0 to get later alphabetical string.

Code:

public class Main {

 public static void main(String[] args) {
 // TODO Auto-generated method stub
 int result;
 String str1 = "Moti";
 String str2 = "Barski";
 result = str1.compareTo(str2);
 String earlierString = (result<0 ? str1:str2);
 if(result==0) {earlierString="same string";}
 System.out.println(earlierString);
 }

}

:albino:

Last edited by Admin on Mon Mar 05, 2018 11:11 am; edited 1 time in total

descriptionjava eclipse oxygen grimoire Emptytry catch finally exception error and thrown ex(ceptions)

more_horiz
java eclipse oxygen grimoire 25jz3b

try catch finally exception error and thrown ex(ceptions)

BTW : import imports packages which are also API.
main class code :

Code:

package errHandler;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
 
 
 public static void main(String[] args) {
 // TODO Auto-generated method stub
 Scanner scanny = new Scanner(System.in);
 try {
 int n1 = 20;
 System.out.println("input 0 to generate ex or IO ex catch runs");
 int n2 = scanny.nextInt(); //
 System.out.println(n1 / n2);
 throw new InputMismatchException("2nd exception option");
 } catch (ArithmeticException e) {
 System.out.println("I caught an exception !!! " + e.getMessage());
 }
 catch (InputMismatchException e) {
 System.out.println("thrown exception worked!!!");
 }
 finally {System.out.println("I run anyways");}
 
 try {
 //exthrower(17);
 exthrower(19); // automatically in try catch because of (see methode declaration line)
 } catch (Exception e) {
 System.out.println("I caught an exception !!! " + e.getMessage());
 e.printStackTrace();
 }
 // stack overflow example
 try {
 selfSummoner();
 } catch (StackOverflowError e) {
 System.out.println("stack overflow error not exception detected");
 }
 }
 
 public static void exthrower(int nx) throws InputMismatchException, Exception {
 if(nx<18) {throw new Exception("no drinks");}else {throw new InputMismatchException("fake IO problem!!!");}
 }
 public static void selfSummoner() {selfSummoner();}
 
 }

descriptionjava eclipse oxygen grimoire Emptyinput output jutsu

more_horiz
to get copy file path option : shift + right click the file
than transform \ to \\ in the file paths you copy paste to the code.

delete single file :

Code:

import java.io.File;

public class Main {

   public static void main(String[] args) {
      //delete directory
      String FilePath ="C:\\Users\\Lenovo\\Desktop\\garbage\\water filter.txt";
      File file = new File(FilePath);
      System.out.println((file.delete() ? "deleted":"can't delete"));
      
   }
}


delete directory (folder) :

Code:

import java.io.File;

public class Main {

   public static void main(String[] args) {
      //delete directory
      String FilePath ="C:\\Users\\Lenovo\\Desktop\\garbage";
      File file = new File(FilePath);
      deleteDirectory(file);
   }
   public static boolean deleteDirectory(File directory) {
      if(directory.exists()) {
         File[] files = directory.listFiles();
         if(null!=files) {
            for (int i = 0; i < files.length; i++) {
               if(files[i].isDirectory()) {
                  deleteDirectory(files[i]);
               }
               else {
                  files[i].delete();
               }
            }
         }
      }
      return (directory.delete());
   }
}


input stream reads char at a time:

Code:

import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

   public static void main(String[] args) throws IOException {
      InputStreamReader isr = new InputStreamReader(System.in);
      System.out.println((char)isr.read());
   }
}


buffered reader : reads strings :
example read from file :

Code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {

   public static void main(String[] args) throws IOException {
      List<String> filecontent = new ArrayList<>();
      String filePath ="C:\\Users\\Lenovo\\Desktop\\HW\\ex.txt";
      try (BufferedReader bReader = new BufferedReader(new FileReader(filePath))){
         String line;
         while((line = bReader.readLine())!=null ){
            if(!line.trim().equals("")) {filecontent.add(line + "\n");}
         }
      } catch (Exception e) {
         // TODO: handle exception
         System.err.println("exception occured");
      }
      System.out.println(filecontent);
   }
}


read web site contents :

Code:

package input.url;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ReadFromSite {
   public static void main(String[] args) throws MalformedURLException {
      List<String> siteContent = new ArrayList<>();
      String url = "http://www.gutenberg.org/files/56679/56679-0.txt";
      URL urlObj = new URL(url);
      try(BufferedReader br = new BufferedReader(new InputStreamReader(urlObj.openStream()))) {
         String row;
         while((row = br.readLine()) != null) {
            siteContent.add(row + "\n");
         }
      }catch (Exception e) {
         // TODO: handle exception
      }
      System.out.println(siteContent.size());
      System.out.println(siteContent);
      
   }
}


output write to file (txt, image, any file):

Code:

package output.file;

import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile {

   public static void main(String[] args) throws IOException {
      String filePath = "C:\\Users\\hackeru\\Desktop\\MyTextFile.txt";
//      String picPath = "C:\\Users\\hackeru\\Pictures\\photoark-lion.ngsversion.1466004832449.png";
      FileWriter fw = new FileWriter(filePath); // by default will overwrite the file
      fw.write("test1");
      fw.close();
      FileWriter fw1 = new FileWriter(filePath, false); // false - to overwrite the file
      fw1.write("test2");
      fw1.close();
      FileWriter fw2 = new FileWriter(filePath, true); // true - to append
      fw2.write("test3");
      fw2.close();
   }

}


descriptionjava eclipse oxygen grimoire Emptyinput drinker

more_horiz
concept : input drinker, gets input from a path :cheers:

Code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class IOManager {
   private FileReader fr = null;

   public List<String> read(String path){
      List<String> data = new ArrayList<>();
      try{
         fr = new FileReader(path);
         BufferedReader br = new BufferedReader(fr);
         String line = null;
         while((line = br.readLine()) != null) {
            data.add(line);
         }
      }
      catch (FileNotFoundException e) {
         e.printStackTrace();
      }
      catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      
      return data;   
   }

}

descriptionjava eclipse oxygen grimoire Emptyjava jar foles and JSON

more_horiz
java eclipse oxygen grimoire 263unt

referencing external java classes/packages/projects (.JAR files)
adding the jar file enables import statements of it's contained packages:

JARing your java project :
in the package explorer right click project name, export, JAVA, JAR file.

importing a JAR :

right click project in the package explorer window
build path, coonfigure build path
click libraries tab, add external JARs
select the JAR file  

if you copy paste the jar file into the project folder :
select add JARS instead of add external JARs
test this with the Json jar:

google : json object maven
1st link :
https://mvnrepository.com/artifact/org.json/json
2nd
version 20180130
3rd
files, view all
4th and final link choose :
json-20180130.jar                                 2018-02-03 21:40     62116  
from :
final link at : http://central.maven.org/maven2/org/json/json/20180130/

select order and export tab(right to libraries tab), and check the JAR
Apply and close. it is now added to the project, under refernce libraries
in the package explorer


JSON :
Json is a universal communication protocol used between programming languages and servers on the intenet
drag the Json file to the project package
to get the json path right click it in the package explorer, properties, copy the path

main code for reading json:

Code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONObject;

public class main {

 public static void main(String[] args) {
 String path = "C:\\Users\\Lenovo\\eclipse-workspace\\Json\\depottest.json";
 System.out.println(printPriceSum(path));// print the json file contents!
 JSONObject jObj = new JSONObject(printPriceSum(path));
// System.out.println(jObj);
// JSONArray jArr = (JSONArray)jObj.get("jeep");
// JSONObject jObj2 = (JSONObject) jArr.get(0);
// System.out.println((Double)jObj2.get("price"));
 double sum = 0;
 for(String s : jObj.keySet()) {
 JSONArray jArr = jObj.getJSONArray(s);
 for (Object object : jArr) {
 sum += ((JSONObject)object).getDouble("price");
 }
 }
 
 System.out.println(sum); // print the sum of the price fields you see in the console output after you run code
 }
 
 public static String printPriceSum(String path) {
 StringBuffer sb = new StringBuffer();
 try (BufferedReader br = new BufferedReader(new FileReader(path))){
 String line = "";
 while((line = br.readLine()) != null) {
 sb.append(line);
 }
 }
 catch (FileNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 
 return sb.toString();
 }

 }


writing a json file:

Code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONObject;

public class main {

 public static void main(String[] args) {
 String path = "C:\\Users\\Lenovo\\eclipse-workspace\\Json\\writeDepottest.json";
 JSONObject phones = new JSONObject();
 phones.put("iPhone", new JSONArray().put(new JSONObject().put("iPhone 7+", 500)));
 phones.getJSONArray("iPhone").put(new JSONObject().put("iPhone 8+", 0));
 phones.getJSONArray("iPhone").getJSONObject(0).put("price", 800);
// phones.getJSONArray("iPhone").getJSONObject(0).put("price", 700); will override the price
 phones.getJSONArray("iPhone").getJSONObject(1).put("price", 900);
 phones.getJSONArray("iPhone").getJSONObject(0).put("color", "Orange");
 System.out.println(phones);
 
 FileWriter fWriter;
 try {
 fWriter = new FileWriter(path);
 fWriter.write(phones.toString());
 fWriter.close();
 
 }
 catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 
 public static String printPriceSum(String path) {
 StringBuffer sb = new StringBuffer();
 try (BufferedReader br = new BufferedReader(new FileReader(path))){
 String line = "";
 while((line = br.readLine()) != null) {
 sb.append(line);
 }
 }
 catch (FileNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 
 return sb.toString();
 }

 }


*** make sure the path directory folder (see code line : C:\\Users\\Lenovo\\eclipse-workspace\\Json\\writeDepottest.json"
exist)

descriptionjava eclipse oxygen grimoire EmptyRe: java eclipse oxygen grimoire

more_horiz
42 JSON CRUD class

key :a car, sub key values: partID name, quantity number, price number

Code:

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonCRUDA{
   private static JSONObject cars = new JSONObject();
   public static JSONObject getCars() {
      return cars;
   }

   public static boolean create(String name, String attributes) {
      // TODO Auto-generated method stub
      String[] strArr = attributes.split(" ");
      cars.put(name, new JSONArray());
      cars.getJSONArray(name).put(new JSONObject());
      for (int i = 0; i < strArr.length / 2; i++) {
         cars.getJSONArray(name).getJSONObject(0).put(strArr[i*2], strArr[i*2+1]);
      }
      System.out.println(cars);
      
      return false;
   }

   public static String Read(String name, String Id, String field) {
      // TODO Auto-generated method stub
      String result="";
      JSONArray jArr = cars.getJSONArray(name);
        for (Object object : jArr) {
          if(((JSONObject)object).get("id").equals(Id))
          {result = ((JSONObject)object).get(field).toString();break;}
        }
      return result;
   }

   public static boolean Update(String name, String Id, String field, String newVal) {
      // TODO Auto-generated method stub
      JSONArray jArr = cars.getJSONArray(name);
        for (Object object : jArr) {
          if(((JSONObject)object).get("id").equals(Id))
          {((JSONObject)object).put(field, newVal);break;}
         
        }
        System.out.println(cars);
      return false;
   }

   public static boolean delete(String name) {
      // TODO Auto-generated method stub
      cars.remove(name);
      System.out.println(cars);
      return false;
   }

   public static boolean Add(String name, String attributes) {
      // TODO Auto-generated method stub
      String[] strArr = attributes.split(" ");
      cars.put(name, new JSONArray());
      cars.getJSONArray(name).put(new JSONObject());
      for (int i = 0; i < strArr.length / 2; i++) {
         cars.getJSONArray(name).put(new JSONObject().put(strArr[i*2], strArr[i*2+1]));
      }
      System.out.println(cars);
      return false;
   }

}


43 sokets and ports exampled with chat console app :
both client and server are main type classes
client side :

Code:

package network.sockets;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ClientSide {

   public static void main(String[] args) {
      try {
         Socket socket = new Socket("localhost", 80); // replace local host with target IP address
         DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
         dos.writeUTF("hadouken");
         
         DataInputStream dis = new DataInputStream(socket.getInputStream());
         System.out.println(dis.readUTF());
         
         dos.flush();
         dos.close();
         System.out.println("Message Sent");
         
      }
      catch (IOException e) {
         // TODO Auto-generated catch block
         System.out.println(e.getMessage());
      }
      

   }

}


server side

Code:

package network.sockets;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSide {

   public static void main(String[] args) {
      try {
         ServerSocket serverSocket = new ServerSocket(80);
         
         Socket socket = serverSocket.accept();
         
         System.out.println("Socket " + socket);
         DataInputStream dis = new DataInputStream(socket.getInputStream());
         String msg = "";
         while(true) {
            msg = dis.readUTF();
            System.out.println(msg);
            DataOutputStream d = new DataOutputStream(socket.getOutputStream());
            d.writeUTF("Received!");
            d.flush();
         }
//         dis.close();
//         socket.close();
      }
      catch (IOException e) {
         System.out.println("Exception?");
         System.out.println(e.getMessage());
      }
   }

}


server with listener (get messages sent by client while it is running)

Code:

package network.sockets;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerWithListener {

   public static void main(String[] args) {
      openSocket();
   }
   private static void openSocket() {
      try {
         listen();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }
   private static void listen() throws IOException {
      ServerSocket serverSocket = new ServerSocket(80);
      
      while(true) {
         Socket socket = serverSocket.accept();
         System.out.println("Socket: " + socket);
         DataInputStream dis = new DataInputStream(socket.getInputStream());
         
         String msg = "";
         try {
            while((msg = dis.readUTF()) != null) {
               System.out.println(msg);
               DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
               dos.writeUTF("Received my nigga");
               dos.flush();
            }
         }catch (EOFException e) {
            continue;
         }
      }
      
   }

}


44 xml parser exampled with rss feed

Code:

package xml.exmp;

package soketEst;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class XMLParserExmp {

   public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
      URL url = new URL("https://9to5mac.com/feed/"); // url of rss feed
      InputStream input = url.openConnection().getInputStream();
      //      InputStream input2 = url.openStream(); // same as .openConnection().getInputStream()

      DocumentBuilderFactory dBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dBuilderFactory.newDocumentBuilder();
      Document document = dBuilder.parse(input);
      printTitle(document.getChildNodes());
   }
   
   static int counter = 0;
   public static void printTitle(NodeList nList) {
      // nList - contains the first NodeList with channel element and 2 #text elements(blank)
      for (int i = 0; i < nList.getLength(); i++) {
         //go through all nodes
         Node tempNode = nList.item(i);
         // checking if the current Node is ELEMENT_NODE or just blank/invalid Node
         if(tempNode.getNodeType() == Node.ELEMENT_NODE) {
            //if the current Node have more child nodes in it recursively run through it
            if(tempNode.hasChildNodes()) {
               printTitle(tempNode.getChildNodes());
            }
            if(tempNode.getNodeName().contains("item")) {
               // get the final list inside the current Node
               NodeList tempList = tempNode.getChildNodes();
               for (int j = 0; j < tempList.getLength(); j++) {
                  if(tempList.item(j).getNodeType() == Node.ELEMENT_NODE) {
                     // Checking if the current Node we're looking for inside
                     // the Final NodeList is "title"
                     if(tempList.item(j).getNodeName().equals("title")) {
                        // Printing the title - getTextContent will return
                        // the text inside the node
                        // for example:
                        //   <title>9to5Mac</title>
                        // will return 9to5Mac
                        System.out.println(++counter + " " + tempList.item(j).getTextContent());
                        System.out.println();
                     }
                  }
               }
            }
         }
      }
   }

}


45 adding auto complete templates :
from top tool strip : window, pref,java,editor, templates

46 threading : running multiple code piles at the same time to achieve faster run time speed
thread class :

Code:

package tasks;

public class thread1 extends Thread {
   int threadID;
   public thread1(int threadID) {
      this.threadID = threadID;
      System.out.println("Thread No." + threadID + " Created!");
   }
   

   @Override
   public void run() {
      for (int i = 0; i < 10; i++) {
         try {
            Thread.sleep(1000);
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         System.out.println("Thread number " + threadID + " Value: " + i);
      }
   }   
}

main :
notice .start activates the run methode as an async method

Code:

package tasks;

public class main {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      thread1 t1 = new thread1(1);
      thread1 t2 = new thread1(2);
      thread1 t3 = new thread1(3);
      t1.start();
      t2.start();
      t3.start();   
      System.out.println("Finished");
      while(t1.isAlive() || t2.isAlive() || t3.isAlive()) {
         System.out.println("Still Alive.");
         try {
            Thread.sleep(1000);
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
      System.out.println("Dead");
   }

}

alternitively (and cleaner )you can use runnable interface :
class :

Code:

package MyThreads.UsingRunnable;

public class ThreadRunnable implements Runnable {
   
   int threadID;
   public ThreadRunnable(int threadID) {
      this.threadID = threadID;
      System.out.println("Thread No." + threadID + " Created!");
      }
   @Override
   public void run() {
      for (int i = 0; i < 10; i++) {
         try {
            Thread.sleep(1000);
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         System.out.println("Thread number " + threadID + " Value: " + i);
      }
   }
}

runnable main :

Code:

package MyThreads.UsingRunnable;

public class TestRunnables {

   public static void main(String[] args) {
      
      Thread[] threads = new Thread[5];
      
      for (int i = 0; i < threads.length; i++) {
         threads[i] = new Thread(new ThreadRunnable(i+1));
      }
      
      for (int i = 0; i < threads.length; i++) {
         threads[i].start();
      }
   }
}

makind a thread wait with .join :

runnable class :

Code:

package MyThreads.Join;

public class ThreadRunnable implements Runnable {
   
   int threadID;
   public ThreadRunnable(int threadID) {
      this.threadID = threadID;
      System.out.println("Thread No." + threadID + " Created!");
      }
   @Override
   public void run() {
      for (int i = 0; i < 10; i++) {
         try {
            Thread.sleep(1000);
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         System.out.println("Thread number " + threadID + " Value: " + i);
      }
   }
}

main with join (t3 waits 4 t1 to finish):

Code:

package MyThreads.Join;

public class TestJoin {

   public static void main(String[] args) {
      
      Thread t1 = new Thread(new ThreadRunnable(1));
      Thread t2 = new Thread(new ThreadRunnable(2));
      Thread t3 = new Thread(new ThreadRunnable(3));
      
      t1.start();
      t2.start();
      if(t1.isAlive()) {
         try {
            t1.join();
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
      
      t3.start();
      
   }
}

:cyclops:

descriptionjava eclipse oxygen grimoire Emptyjava threads walkthrough pt2

more_horiz


threads level 2:

setting thread priority :
class :

Code:

package MyThreads.Priority;

public class ThreadsPriority implements Runnable {
   int threadID;
   
   public ThreadsPriority(int threadID) {
      this.threadID = threadID;
   }
   @Override
   public void run() {
      System.out.println(threadID);
   }

}

main :

Code:

package MyThreads.Priority;

public class MainClass {

   public static void main(String[] args) {      
      Thread t1 = new Thread(new ThreadsPriority(1));
      Thread t2 = new Thread(new ThreadsPriority(2));
      Thread t3 = new Thread(new ThreadsPriority(3));
      
      t1.setPriority(Thread.MIN_PRIORITY);
      t2.setPriority(Thread.NORM_PRIORITY);
      t3.setPriority(Thread.MAX_PRIORITY);
      // 1 - 4 = min - below normal
      // 5 - 9 = normal - below high
      // 10 = high priority
      // 5 - Default priority value
      t3.start();
      t2.start();
      t1.start();
   }

}

firing up tasks in specified order :

class :

Code:

package MyThreads.RaceCondition;



public class RaceCondition implements Runnable {
   public int counter = 0;
   static int threadID = 0;
   // Async.
//   public  void add() {
//      System.out
//      .println(String.format("Thread %d value: %d", ++counter, ++threadID));
//   }
   public synchronized void add() {
      System.out
      .println(String.format("Thread %d value: %d", ++counter, ++threadID));
   }
   @Override
   public void run() {
      add();

   }
}

Main :

Code:

package MyThreads.RaceCondition;

public class Main {

   public static void main(String[] args) {
      RaceCondition rc1 = new RaceCondition();
      
      Thread t1 = new Thread(rc1);
      Thread t2 = new Thread(rc1);
      Thread t3 = new Thread(rc1);
      
      
      t1.start();
      t2.start();
      t3.start();
      System.out.println("Main counter value: " + rc1.counter);
      
   }

}

interupting a task :
class :

Code:

package MyThreads.Interrupt;

public class MyThread implements Runnable {
   int threadID;
   
   public MyThread(int threadID) {
      this.threadID = threadID;
   }
   
   @Override
   public void run() {
      
      for (int i = 0; i < 10; i++) {
         System.out.println("Thread: " + threadID + " value: " + i);
         
         try {
            Thread.currentThread().sleep(1000);
         } catch (InterruptedException e) {
            System.out.println("Thread " + threadID + " Interrupted");
            break;
         }
      }
      System.out.println("Exit...");
   }
   
}


main with interuption :

Code:

package MyThreads.Interrupt;

public class Main {

   public static void main(String[] args) {
      Thread[] threads = new Thread[5];
      
      for (int i = 0; i < threads.length; i++) {
         threads[i] = new Thread(new MyThread(i+1));
      }
      
      for (int i = 0; i < threads.length; i++) {
         threads[i].start();
      }
      
      threads[1].interrupt();
      
   }

}

daemon threads : they run outside of the main program, closing them does not close the main program.
the mewtwo of threads:
daemon class :

Code:

package MyThreads.DaemonThreads;

public class DaemonThread implements Runnable {
int threadID;
   
   public DaemonThread(int threadID) {
      this.threadID = threadID;
   }
   @Override
   public void run() {
      for (int i = 0; i < 10; i++) {
         this.threadID += i;
         try {
            Thread.sleep(1000);
         } catch (InterruptedException e) {

            e.printStackTrace();
         }
      }
   }
}


main:

Code:

package MyThreads.DaemonThreads;

public class Main {

   public static void main(String[] args) {
      Thread t1 = new Thread(new DaemonThread(1));
      // This thread can run even when the JVM closed
      t1.setDaemon(true);
//      User Thread - Default - when JVM/App is closed - the Thread is dead
//      t1.setDaemon(false);
      t1.start();
      
   }

}

sync ing threads to objects (locks) within code blocks:
class:

Code:

package MyThread.Sync;

import com.sun.org.apache.bcel.internal.generic.NEW;

public class SyncBlock implements Runnable {
   public int counter = 0;
   static int threadID = 0;
   Object lock = new Object();
   public void add() {
      synchronized (lock) {
         System.out
         .println(String.format("Thread %d value: %d", ++counter, ++threadID));
      }
   }
   @Override
   public void run() {
      add();
   }

}

main:

Code:

package MyThread.Sync;

public class Main {

   public static void main(String[] args) {
      SyncBlock rc1 = new SyncBlock();
      
      Thread t1 = new Thread(rc1);
      Thread t2 = new Thread(rc1);
      Thread t3 = new Thread(rc1);
      
      
      t1.start();
      t2.start();
      t3.start();
      System.out.println("Main counter value: " + rc1.counter);

   }

}

example of an error causer dead locking two objects :
class :

Code:

package MyThread.Sync;

public class DeadLock {
   static Object lock1 = new Object();
   static Object lock2 = new Object();
   
   public static void main(String[] args) {
      Thread t1 = new Thread(new DL1());
      Thread t2 = new Thread(new DL2());
      t1.start();
      t2.start();
      
   }
   public static class DL1 implements Runnable{

      @Override
      public void run() {
         System.out.println("Start");
         synchronized (lock1) {
            System.out.println("Thread 1: Holding lock1");
            
            try {
               Thread.sleep(100);
            } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
            
            System.out.println("Moving to lock2");
            synchronized (lock2) {
               System.out.println("Thread 1: Holding lock2");
            }
         }
         System.out.println("End");
         
      }
      
   }
   
   public static class DL2 implements Runnable{

      @Override
      public void run() {
         synchronized (lock2) {
            System.out.println("Thread 1: Holding lock2");
            
            try {
               Thread.sleep(100);
            } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
            
            System.out.println("Moving to lock1");
            synchronized (lock1) {
               System.out.println("Thread 1: Holding lock1");
            }
         }
         
      }
      
   }
   
}



descriptionjava eclipse oxygen grimoire EmptyRe: java eclipse oxygen grimoire

more_horiz
java eclipse oxygen grimoire 2721z9

encode file data to base 64 data file :
main :

Code:

package encode.base64;

import java.util.Arrays;
import java.util.Base64;

public class EncodingBase64 {

   public static void main(String[] args) {
      String data = "Lorem ipsum dolor sit amet, consectetuer in. In vitae mauris natoque, mi vestibulum vestibulum nulla consequat, pellentesque nemo, lobortis ultrices commodo elit proin non, dignissim quis praesent.";
      Base64.Encoder encoder = Base64.getEncoder();
      byte[] encoded = encoder.encode(data.getBytes());
      System.out.println(Arrays.toString(encoded));
      for (int i = 0; i < encoded.length; i++) {
         System.out.print((char)encoded[i]);
         if(i != 0 && i % 4 == 0) {
            System.out.print(" ");
         }
      }
//      encoded[14] = 62;
      System.out.println();
      Base64.Decoder decoder = Base64.getDecoder();
      byte[] decoded = decoder.decode(encoded);
//      System.out.println(Arrays.toString(decoded));
      System.out.println(new String(decoded));

   }

}


the file is now wierd

decode base 64 data file to its old self :
main :

Code:

package decode.base64.file;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;

public class DecodeFile {

   public static void main(String[] args) {
      String path = "C:\\Users\\hackeru\\Downloads\\";
      try {
         decodeFile(path);
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }
   public static void decodeFile(String path) throws IOException {
      FileOutputStream fos = new FileOutputStream(path + "new.jpg");
      Base64.Decoder decoder = Base64.getMimeDecoder();
      InputStream fis = decoder.wrap(new FileInputStream(path + "1.jpg.1encoded"));
      int bytes;
      while((bytes = fis.read()) != -1) {
         fos.write(bytes);
      }
      fis.close();
      fos.close();
   }
}

descriptionjava eclipse oxygen grimoire Emptyauto program design pattern cerabellum level 1

more_horiz
©️ example for java project using MB's cerebellum AP algorithm 1st ver.
uses menu, menu choice adaptation to action, filter of actions and flexibility for special extra actions
and simultaneous actions as well as timed actions. ❤
project smart house
Moti Barski
menu pattern jutsu :

main :
package SmartHouse;

Code:

// by Moti Barski
import java.io.IOException;
import java.text.ParseException;

import javax.xml.parsers.ParserConfigurationException;

//import org.w3c.dom.Node;
//import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Main {

   public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, ParseException {
      doit hadouken = doit.newInstance();
      hadouken.work();
   }
}


doit class :

Code:

package SmartHouse;

import java.text.ParseException;

public class doit {
   // singleton patterned class : populate menu class and exe the program, keeps
   // code hidden from main.
   private static doit doit1; // array this to get x number of singletons enabled

   private doit() {
   }

   public static doit newInstance() {
      if (doit1 == null) {
         doit1 = new doit();
      }
      return doit1;
   }

   public void work() {
      // populate menu options
      menu.AddChoices("0", "\n1.light\n2.boiler\n3.tv\n4.doors\n5.sync lights to kitchen");
      menu.AddChoices("01", "\nwhich room ?\n1.one\n2.two\n3.three\n4.kitchen\n5.living room");
      menu.AddChoices("03", "\nwhich room ?\n1.one\n2.two\n3.three\n4.kitchen\n5.living room");
      menu.AddChoices("04", "\nwhich room ?\n1.one\n2.two\n3.three\n4.kitchen\n5.living room");
      menu.preRegexMenu("02", "\nwhen ? type in time range");
      // create the mock microcontroller
      audrino32Pins audrino32Pins = new audrino32Pins();
      while (true) {
         audrino32Pins.getStatusOfHouse();
         menu.useMenu();
         // convert user menu choice to audrino pin :
         requestAdapterLv1 requestAdapterLv1 = new requestAdapterLv1(menu.getSelection());
         // filter out invalid requests and exe :
         try {
            requestFilter.fireUpRequest(audrino32Pins, requestAdapterLv1);
         } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         }

   }
}


mock audrino class :

Code:

package SmartHouse;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

public class audrino32Pins {
   // mock MC class with 2 nested classes
   private boolean[] pinArray = new boolean[32];

   public boolean[] getPinArray() {
      return pinArray;
   }

   public void openPin(int pinNum) throws IOException, ParserConfigurationException, SAXException {
      pinArray[pinNum] = true;
      VR vr1 = new VR();
      vr1.extendedAction(pinNum);
   }

   public void closePin(int pinNum) {
      pinArray[pinNum] = false;
   }

   public void switchPin(int pinNum) throws IOException, ParserConfigurationException, SAXException {
      // FLIP ! monster's effect activates.
      pinArray[pinNum] = !pinArray[pinNum];
      if (pinArray[pinNum]) {
         VR vr1 = new VR();
         vr1.extendedAction(pinNum);
      }
   }

   public void getStatusOfHouse() {
      houseStatus hs1 = new houseStatus();
      hs1.getStatus(this);
   }

   private class houseStatus {
      /*
       * legend : 1-6 lights 7 boiler 8-11 tv 12-15 doors 16 living room light 17
       * living room TV living room has no door
       */
      public void getStatus(audrino32Pins a32p) {
         if (a32p.pinArray[1]) {
            System.out.println("light in room 1 on");
         } else {
            System.out.println("light in room 1 off");
         }
         if (a32p.pinArray[2]) {
            System.out.println("light in room 2 on");
         } else {
            System.out.println("light in room 2 off");
         }
         if (a32p.pinArray[3]) {
            System.out.println("light in room 3 on");
         } else {
            System.out.println("light in room 3 off");
         }
         if (a32p.pinArray[4]) {
            System.out.println("lights in kitchen on");
         } else {
            System.out.println("lights in kitchen off");
         }
         if (a32p.pinArray[7]) {
            System.out.println("boiler on");
         } else {
            System.out.println("boiler off");
         }

         if (a32p.pinArray[8]) {
            System.out.println("tv in room 1 on");
         } else {
            System.out.println("tv in room 1 off");
         }
         if (a32p.pinArray[9]) {
            System.out.println("tv in room 2 on");
         } else {
            System.out.println("tv in room 2 off");
         }
         if (a32p.pinArray[10]) {
            System.out.println("tv in room 3 on");
         } else {
            System.out.println("tv in room 3 off");
         }
         if (a32p.pinArray[11]) {
            System.out.println("tv in kitchen on");
         } else {
            System.out.println("tv in kitchen off");
         }

         if (a32p.pinArray[12]) {
            System.out.println("door room 1 open");
         } else {
            System.out.println("door room 1 locked");
         }
         if (a32p.pinArray[13]) {
            System.out.println("door room 2 open");
         } else {
            System.out.println("door room 2 locked");
         }
         if (a32p.pinArray[14]) {
            System.out.println("door room 3 open");
         } else {
            System.out.println("door room 3 locked");
         }
         if (a32p.pinArray[15]) {
            System.out.println("door in kitchen open");
         } else {
            System.out.println("door in kitchen locked");
         }
         if (a32p.pinArray[16]) {
            System.out.println("light in living room on");
         } else {
            System.out.println("light in living room off");
         }
         if (a32p.pinArray[17]) {
            System.out.println("tv in living room on");
         } else {
            System.out.println("tv in living room off");
         }
         // if (a32p.pinArray[18]) {
         // System.out.println("door in living room open");
         // } else {
         // System.out.println("door in living room locked");
         // }
      }
   }

   private class VR {
      /*
       * legend : 1-4 lights 7 boiler 8-11 tv 12-15 doors
       */
      public void extendedAction(int pin) throws IOException, ParserConfigurationException, SAXException {
         switch (pin) {
         case 8:
            System.out.println("tv in room 1 is on");
            vod.showListDisplay("https://nyaa.si/?page=rss&q=1080&c=0_0&f=0");
            break;
         case 9:
            System.out.println("tv in room 2 is on");
            vod.showListDisplay("https://nyaa.si/?page=rss&q=1080&c=0_0&f=0");
            break;
         case 10:
            System.out.println("tv in room 3 is on");
            vod.showListDisplay("https://nyaa.si/?page=rss&q=1080&c=0_0&f=0");
            break;
         case 11:
            System.out.println("tv in kitchen is on");
            vod.showListDisplay("https://nyaa.si/?page=rss&q=1080&c=0_0&f=0");
         case 17:
            System.out.println("tv in living room is on");
            vod.showListDisplay("https://nyaa.si/?page=rss&q=1080&c=0_0&f=0");
            break;
         default:
            break;
         }
      }
   }
}


menu class :

Code:

package SmartHouse;

import java.util.HashSet;
import java.util.Hashtable;
import java.util.Scanner;

public class menu {
   // menu container
   private static Hashtable<String, String> hashtable = new Hashtable<>();
   // menus with regex marker
   private static HashSet<String> preRegex = new HashSet<String>();
   private static Scanner s1 = new Scanner(System.in);
   // user selection
   private static String selection = "0";



   public static void AddChoices(String choice, String subMenu) {
      hashtable.put(choice, subMenu);
   }

   public static void preRegexMenu(String choice, String subMenu) {
      hashtable.put(choice, subMenu);
      preRegex.add(choice);
   }
   public static void useMenu() {
      if (hashtable.containsKey(selection) && !selection.contains("exit")) {
         System.out.println(hashtable.get(selection));
         if (preRegex.contains(selection)) {
            selection += " ";
         }
         selection += s1.nextLine();
         useMenu();
      } else {
         if (selection.contains("exit")) {
            selection = "0";
         }
      }
      }

   public static String getSelection() {
      // TODO Auto-generated method stub
      String result = selection;
      selection = "0";
      return result;
   }
   }


timed task class to summon actions at set time :

Code:

package SmartHouse;

import java.io.IOException;
import java.util.TimerTask;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

public class MyTimeTask extends TimerTask {
   // summons task at needed time
   private int pin;
   private pinAction pA;
   private audrino32Pins audi;

   public MyTimeTask(int pin, pinAction pA, audrino32Pins audi) {
      super();
      this.pin = pin;
      this.pA = pA;
      this.audi = audi;
   }

   @Override
   public void run() {
      switch (pA) {
      case open:
         try {
            audi.openPin(pin);
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         break;
      case close:
         audi.closePin(pin);
         break;
      case flip:
         try {
            audi.switchPin(pin);
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         break;
      default:
         break;
   }
   }
}


audrino pin action enumeration :

Code:

package SmartHouse;

public enum pinAction {
   open, close, flip
}


pin task class :

Code:

package SmartHouse;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

public class pinTask  extends Thread {
   private int pin;
   private pinAction pA;
   private audrino32Pins audi;

   public pinTask(int pin, pinAction pA, audrino32Pins audi) {
      super();
      this.pin = pin;
      this.pA = pA;
      this.audi = audi;
   }

   @Override
   public void run() {
      // TODO Auto-generated method stub
      System.out.println("works");
      switch (pA) {
      case open:
         try {
            audi.openPin(pin);
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         break;
      case close:
         audi.closePin(pin);
         break;
      case flip:
         try {
            audi.switchPin(pin);
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         break;
      default:
         break;
      }
   }

}


request adapter class :

Code:

package SmartHouse;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class requestAdapterLv1 {
   private String startTime = "";
   private String endTime = "";
   private int pin = 5000;

   public String getStartTime() {
      return startTime;
   }

   public String getEndTime() {
      return endTime;
   }

   public int getPin() {
      return pin;
   }

   public requestAdapterLv1(String selection) {
      super();
      this.startTime = "";
      this.endTime = "";
      this.pin = 5000;
      byte regexCounter = 0;
      // regexChecker("([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])",selection);
      Pattern checkRegex = Pattern.compile("([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]");
      // Creates a Matcher object that searches the String for
      // anything that matches the REGEX
      Matcher regexMatcher = checkRegex.matcher(selection);
      // Cycle through the positive matches and print them to screen
      // Make sure string isn't empty and trim off any whitespace
      while (regexMatcher.find() && regexCounter < 2) {
         regexCounter++;
         if (regexMatcher.group().length() != 0) {
            if (regexCounter == 1) {
               startTime = regexMatcher.group().trim();
            } else {
               endTime = regexMatcher.group().trim();
            }
         }
      }
      selection += " ";
      selection = selection.substring(0, selection.indexOf(" "));
      switch (selection) {
      case "011":
         pin = 1;
         break;
      case "012":
         pin = 2;
         break;
      case "013":
         pin = 3;
         break;
      case "014":
         pin = 4;
         break;
      case "02":
         pin = 7;
         break;
      case "05":
         pin = 4000;
         break;
      case "031":
         pin = 8;
         break;
      case "032":
         pin = 9;
         break;
      case "033":
         pin = 10;
         break;
      case "034":
         pin = 11;
         break;
      case "041":
         pin = 12;
         break;
      case "042":
         pin = 13;
         break;
      case "043":
         pin = 14;
         break;
      case "044":
         pin = 15;
         break;
      case "015":
         pin = 16;
         break;
      case "035":
         pin = 17;
         break;
      default:
         break;
      }
   }

   private static void regexChecker(String theRegex, String str2Check) {
      // You define your regular expression (REGEX) using Pattern
      Pattern checkRegex = Pattern.compile(theRegex);
      // Creates a Matcher object that searches the String for
      // anything that matches the REGEX
      Matcher regexMatcher = checkRegex.matcher(str2Check);
      // Cycle through the positive matches and print them to screen
      // Make sure string isn't empty and trim off any whitespace
      while (regexMatcher.find()) {
         if (regexMatcher.group().length() != 0) {
            System.out.println(regexMatcher.group().trim());
            // You can get the starting and ending indexs
            System.out.println("Start Index: " + regexMatcher.start());
            System.out.println("Start Index: " + regexMatcher.end());
         }
      }
      System.out.println();
   }
}


request filter class : (for conditions and stuff like that)

Code:

package SmartHouse;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

public class requestFilter {
   public static boolean fireUpRequest(audrino32Pins audi1, requestAdapterLv1 RAL1) throws ParseException {
      // if door open light can't turn off
      /*
       * legend : 1-6 lights 7 boiler 8-11 tv 12-15 doors
       */
      if (audi1.getPinArray()[12] && audi1.getPinArray()[1] && RAL1.getPin() == 1) {
         System.out.println("door open can't shut off light");
         return false;
      }
      if (audi1.getPinArray()[13] && audi1.getPinArray()[2] && RAL1.getPin() == 2) {
         System.out.println("door open can't shut off light");
         return false;
      }
      if (audi1.getPinArray()[14] && audi1.getPinArray()[3] && RAL1.getPin() == 3) {
         System.out.println("door open can't shut off light");
         return false;
      }
      if (audi1.getPinArray()[15] && audi1.getPinArray()[4] && RAL1.getPin() == 4) {
         System.out.println("door open can't shut off light in kitchen");
         return false;
      }

      // can't turn on boiler between 8 to 12
      if (RAL1.getPin() == 7) {
         if (RAL1.getStartTime() == "" || RAL1.getEndTime() == "") {
            System.out.println("choose time range between 8 -12 to engage boiler");
            return false;
         } else {
            DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            java.util.Date date = dateFormatter.parse("1955-11-05 " + RAL1.getStartTime());
            java.util.Date date2 = dateFormatter.parse("1955-11-05 " + RAL1.getEndTime());
            if (!(date.getHours() >= 8) || !(date2.getHours() <= 11)) {
               System.out.println("choose time range between 8 -12 to engage boiler");
               return false;
            } else {
               Calendar cal = Calendar.getInstance();
               SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

               Timer timer = new Timer();
               int h = date.getHours() - cal.getTime().getHours();
               int m = date.getMinutes() - cal.getTime().getMinutes();
               int s = date.getSeconds() - cal.getTime().getSeconds();
               int delay = h * 3600000 + m * 60000 + s * 1000;
               if (delay < 0) {
                  delay += 24 * 24 * 3600000;
               }

               timer.schedule(new MyTimeTask(RAL1.getPin(), pinAction.open, audi1), delay);

               Timer timer2 = new Timer();
               int h2 = date2.getHours() - cal.getTime().getHours();
               int m2 = date2.getMinutes() - cal.getTime().getMinutes();
               int s2 = date2.getSeconds() - cal.getTime().getSeconds();
               int delay2 = h * 3600000 + m * 60000 + s * 1000;
               if (delay2 < 0) {
                  delay2 += 24 * 24 * 3600000;
               }

               timer.schedule(new MyTimeTask(RAL1.getPin(), pinAction.close, audi1), delay2);
               return true;
            }
         }

      }
      // kithchen light case :
      if (RAL1.getPin() == 4000) {
         ArrayList<Integer> x = new ArrayList<>();
         int syncCounter = 0;
         if (!(audi1.getPinArray()[12] && audi1.getPinArray()[1])
               && (audi1.getPinArray()[4] != audi1.getPinArray()[1])) {
            x.add(1);
            syncCounter++;
         }
         if (!(audi1.getPinArray()[13] && audi1.getPinArray()[2])
               && (audi1.getPinArray()[4] != audi1.getPinArray()[2])) {
            x.add(2);
            syncCounter++;
         }
         if (!(audi1.getPinArray()[14] && audi1.getPinArray()[3])
               && (audi1.getPinArray()[4] != audi1.getPinArray()[3])) {
            x.add(3);
            syncCounter++;
         }
         if (audi1.getPinArray()[4] != audi1.getPinArray()[16]) {
            x.add(16);
            syncCounter++;
         }
         if (syncCounter > 0) {
            ArrayList<pinTask> pTasks = new ArrayList<>();
            for (Integer intx : x) {
               pTasks.add(new pinTask(intx, pinAction.flip, audi1));
            }
            for (pinTask ptx : pTasks) {
               ptx.start();
            }
         try {
               pTasks.get(0).join();
            } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
               e1.printStackTrace();
         }
            System.out.println(syncCounter + " lights synced");
         return true;

         } else {
            return false;
         }
      } else {

         if (!(RAL1.getPin() == 5000)) {
            // Thread t1 = new Thread(new pinTasks(RAL1.getPin(), pinAction.flip, audi1));
            // t1.start();
            try {
               audi1.switchPin(RAL1.getPin());
            } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            } catch (ParserConfigurationException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            } catch (SAXException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
            return true;
         }
      }
      return false;
   }

}

vod class :
(uses rss feed ):

Code:

package SmartHouse;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Hashtable;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class vod {
   private static int counter = 0;
   private static Hashtable<String, String> hashtable = new Hashtable<>();

   public static void showListDisplay(String rssUrl) throws IOException, ParserConfigurationException, SAXException {
      URL url = new URL(rssUrl); // url of rss feed
      InputStream input = url.openConnection().getInputStream();

      DocumentBuilderFactory dBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dBuilderFactory.newDocumentBuilder();
      Document document = dBuilder.parse(input);
      System.out.println("select show");
      printTitle(document.getChildNodes());
      Scanner s1 = new Scanner(System.in);
      System.out.println("now playing: " + hashtable.get(s1.next()));
   }
   public static void showListDisplay() throws IOException, ParserConfigurationException, SAXException {
      URL url = new URL("https://nyaa.si/?page=rss&q=1080&c=0_0&f=0"); // url of rss feed
      InputStream input = url.openConnection().getInputStream();

      DocumentBuilderFactory dBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dBuilderFactory.newDocumentBuilder();
      Document document = dBuilder.parse(input);
      printTitle(document.getChildNodes());
   }

   private static void printTitle(NodeList nList) {
      for (int i = 0; i < nList.getLength(); i++) {
         // go through all nodes
         Node tempNode = nList.item(i);
         // checking if the current Node is ELEMENT_NODE or just blank/invalid Node
         if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
            // if the current Node have more child nodes in it recursively run through it
            if (tempNode.hasChildNodes()) {
               printTitle(tempNode.getChildNodes());
            }
            if (tempNode.getNodeName().contains("item")) {
               // get the final list inside the current Node
               NodeList tempList = tempNode.getChildNodes();
               for (int j = 0; j < tempList.getLength(); j++) {
                  if (tempList.item(j).getNodeType() == Node.ELEMENT_NODE) {
                     // Checking if the current Node we're looking for inside
                     // the Final NodeList is "title"
                     if (tempList.item(j).getNodeName().equals("title")) {

                        System.out.println(++counter + " " + tempList.item(j).getTextContent());
                        hashtable.put(counter + "", tempList.item(j).getTextContent());
                        System.out.println();
                     }
                  }
               }
            }
         }
      }
   }
}





descriptionjava eclipse oxygen grimoire Emptyjava accessing the sort logic

more_horiz
class :

Code:

package sortX;

import java.util.Comparator;

public class MySort implements Comparator<Integer> {

   @Override
   public int compare(Integer x, Integer y) {
      // access hya

      return y.compareTo(x);
   }

}


main class :

Code:

package sortX;

import java.util.Arrays;

public class main {

   public static void main(String[] args) {
      // TODO Auto-generated method stub
      Integer[] primes = { 2, 7, 5, 3, 11 };
      Arrays.sort(primes, new MySort());
      System.out.println(Arrays.toString(primes));
      
      
   }

}

:twisted: :roll:

descriptionjava eclipse oxygen grimoire Emptyjava queue

more_horiz

Code:

import java.util.*;  
class TestCollection12{  
public static void main(String args[]){  
PriorityQueue<String> queue=new PriorityQueue<String>();  
queue.add("megamen");  
queue.add("shuki");  
queue.add("jin");  
queue.add("whisky");  
queue.add("paull");  
System.out.println("head:"+queue.element());  
System.out.println("head:"+queue.peek());  
System.out.println("iterating the queue elements:");  
Iterator itr=queue.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  
queue.remove();  
queue.poll();  
System.out.println("after removing two elements:");  
Iterator<String> itr2=queue.iterator();  
while(itr2.hasNext()){  
System.out.println(itr2.next());  
}  
}  
}  


if you are using custom objects in the queue,
said object classes must implement comparable, other wise
the queue will error after adding a 2nd object. :


public class ObjectX implements Comparable<ObjectX>

:s37:

descriptionjava eclipse oxygen grimoire EmptyJava HashMap getOrDefault() Example

more_horiz
_

Code:

package com.javatutorialhq.java.examples;

import java.util.HashMap;

/*
 * This example source code demonstrates the use of  
 * getOrDefault() method of HashMap class
 */

public class HashMapGetOrDefaultExample {

 public static void main(String[] args) throws InterruptedException {

 int idNum = 666;
 HashMap<Integer, String> map = init();
 System.out.println("Student with id number " + idNum + " is "
 + map.getOrDefault(idNum, "John Doe"));

 }

 private static HashMap<Integer, String> init() {
 // declare the hashmap
 HashMap<Integer, String> mapStudent = new HashMap<>();
 // put contents to our HashMap
 mapStudent.put(7688, "leefy tree");
 mapStudent.put(98544, "spicy sup");
 return mapStudent;
 }

}

:shine:

descriptionjava eclipse oxygen grimoire Emptymulti thread jutsu

more_horiz
1 : https://java2blog.com/java-cyclicbarrier-example/

2 : using threads :

accelerator (where you put the actual shit you want to run):

Code:

public class Accelarator implements Runnable {
    int threadID;

    public Accelarator(int threadID) {
        this.threadID = threadID;
        System.out.println("Thread No." + threadID + " Created!");
    }

    @Override
    public void run() {
        // for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(0);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        System.out.println("Thread number " + threadID + " Value: ");
        // System.out.println("Thread number " + threadID + " Value: " + i);
        // }
    }
}


main class :

Code:

public class Main3 {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        Thread[] threads = new Thread[5];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Accelarator(i + 1));
        }

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        System.out.println("shit");
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Accelarator(i + 1));
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
    }
}


output :

Thread No.1 Created!
Thread No.2 Created!
Thread No.3 Created!
Thread No.4 Created!
Thread No.5 Created!
Thread number 1 Value:
Thread number 3 Value:
Thread number 2 Value:
Thread number 4 Value:
Thread number 5 Value:
shit
Thread No.1 Created!
Thread No.2 Created!
Thread No.3 Created!
Thread No.4 Created!
Thread No.5 Created!
Thread number 4 Value:
Thread number 5 Value:
Thread number 2 Value:
Thread number 3 Value:
Thread number 1 Value:


here is the output when I comment out the join :

Code:

for (Thread thread : threads) {
//            thread.join();
//        }



Thread No.1 Created!
Thread No.2 Created!
Thread No.3 Created!
Thread No.4 Created!
Thread No.5 Created!
Thread number 2 Value:
Thread number 3 Value:
Thread number 4 Value:
shit
Thread No.1 Created!
Thread number 5 Value:
Thread number 1 Value:
Thread No.2 Created!
Thread No.3 Created!
Thread No.4 Created!
Thread No.5 Created!
Thread number 1 Value:
Thread number 3 Value:
Thread number 4 Value:
Thread number 5 Value:
Thread number 2 Value:


it becomes diarrhea

combind results can be placed in the thread or cyclicbarrier global vars for retrival after
they all finish

:pirat:

descriptionjava eclipse oxygen grimoire EmptyRe: java eclipse oxygen grimoire

more_horiz
online java compiler :

https://www.beta.browxy.com/

it also lets you share codes and save and stuff
privacy_tip Permissions in this forum:
You cannot reply to topics in this forum
power_settings_newLogin to reply