Saturday, April 30, 2016

Even / Odd Array Index

In some cases, you might have to process array values where only every other value needs to be processed.  This example should help you understand the process including how to use Regular Expressions.  


public class GradeSplit{
      public static void main(String[] args){
            String input="claude 99 mike 89 paul 88";
            //Review regular expression syntax
            //https://docs.oracle.com/javase/7/docs/api/
            // \\s will split on white space and the + is matching the white 

            //        space character one or more times
            //Look at the Java API's String class split method, you'll see that it returns a String[]
            //Thus every even index will hold names ( generate even index numbers by 2*i )
            //and every odd index will hold the grade value ( generate odd index values by 2*i+1 )

            String[] data=input.split("\\s+");
            
//Since you always have pairs of values, divide the length by 2 
             //to generate an array holding only the grades
            int[] x=new int[data.length/2];                       //add break point and examine data array

            //fill the array to hold grades by parsing all odd index values
            for(int i=0;i<x.length;i++){
                   x[i]=Integer.parseInt(data[2*i+1]);      
//add break point and step through the loop
             }

 
          //print all even values from the original array and all values 
            //from the grade array - processed as parallel array
            for(int i=0;i<x.length;i++){
                  System.out.printf("Your name is: %-6s and your grade is: %3d\n", data[2*i],x[i]);
            }
      }
}


Thus you can calculate the index value to use in your code by simple arithmetic calculations. Computer Science is about problem solving by pattern recognition where pattern recognition does not work without writing things down on paper in a logical fashion until a pattern emerge.

index odd values even values
index*2+1 index*2
0 1 0
1 3 2
2 5 4
3 7 6
4 9 8
5 11 10
6 13 12


Contents of data array after the split operation.




Contents of x integer array that is half of the data array and now only containing values as integers.

 



Output of code above
Your name is: claude and your grade is:  99
Your name is: mike    and your grade is:  89
Your name is: paul     and your grade is:  88


Tuesday, April 26, 2016

Create Runnable JAR File in Eclipse

Create a project in Eclipse.
Add a package practice
Add all three source code as separate source files into the practice package
Set Run Configurations... to have Main class as practice.MyEffort
Compile and make sure it runs
Export the project as Runnable JAR file
Double click on the result to see your program run


package practice;

import javax.swing.JOptionPane;

/** This class will be used as a driver class for the application
*@author Zoltan Szabo
*@version 1.0.0
*/
public class MyEffort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Alphabet letters=new Alphabet();
        String word;
        //char answer;
        int answer;
        do{
            word=JOptionPane.showInputDialog(null,"Please, enter a single word you'd like to convert to a percentage.","Word 2 Effort",JOptionPane.QUESTION_MESSAGE);
            Word2Percentage result=new Word2Percentage(word,letters);
            StringBuilder msg=new StringBuilder("The effort you put in your work is: "+result.getResult()+"%");

            JOptionPane.showMessageDialog(null, msg.toString(),"Answer",JOptionPane.INFORMATION_MESSAGE);
           
            //answer=JOptionPane.showInputDialog("Would you like to convert another word?(y/n): ").charAt(0);
            //answer=Character.toUpperCase(answer);
            answer=JOptionPane.showConfirmDialog(null,"Would you like to convert another word?","Convert Another One!!!",JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE );
            if ( answer == 0){
                continue;
            }
            else if (answer == 1){
                JOptionPane.showMessageDialog(null,"Thank you for using this application, hope to see you again soon!!!","Good Bye",JOptionPane.INFORMATION_MESSAGE);
                break;
            }
            else{
                JOptionPane.showMessageDialog(null,"Invalid selection, bye!!!","Good Bye",JOptionPane.INFORMATION_MESSAGE);
                break;
            }
        } while (answer == 0);
    }
}


 package practice;

/**This is a class that populates an array with alphabet characters using a loop
 * @author Zoltan
 * @version 1.0.0

 */
public class Alphabet {
     
/**
 * The field representing a value
 */
public final static int SIZE=26;   
private Character letters[];

/**
 * Class constructor of Driver class with no particular function in this example
 * @param value as an integer
 */
public Alphabet(){
    letters=new Character[SIZE];
    for(int i=0;i<SIZE;i++)
        letters[i]=(char) ('A'+i);
}

/**This method will return a character corresponding to its index value
 * @param index of character
 * @return character at index
 */
public char getCharacter(int index){
    return letters[index].charValue();
}

}

package practice;

/**Class that converts the given word to a percentage representation
*@author Zoltan Szabo
*@version 1.0.0
*/
public class Word2Percentage {
private int total;

/**Constructor to the class
*@param word the user supplied word
*@param toConvert the corresponding array where the index value will be used to convert each character to a numerical value
*/
public Word2Percentage(String word, Alphabet toConvert) {
        super();

        String temp_word=word.toUpperCase();
        for (int i = 0; i < temp_word.length(); i++){
            for (int j = 0; j < Alphabet.SIZE; j++){
                if (toConvert.getCharacter(j) == temp_word.charAt(i)){
                    total += (j + 1);
                }
            }
        }
    }

/**Method to return the final converted numerical value representation of the given word
*@return numerical value of given word
*/
    public int getResult(){
        return total;
    }

}


Wednesday, May 27, 2015

Quick Recursive Example

This class can be used to drive the example classes below

public class Driver{
    public static void main(String argv[]){
        Factorial value=new Factorial(4);
        System.out.println(value.getValue());
        Fibonacci value2=new Fibonacci(10);
        System.out.println(value2.getValue());
    }
}

Since factorial(1) is 1, we can use that as a stop value to end the recursive process.  Thus, you need to trace the process by hand on a piece of paper before reading the code below of designing your own algorithm. 

          Factorial(4) = Factorial(4)*Factorial(3)*Factorial(2)*Factorial(1)
          Factorial(1) = 1
          Factorial(2) = 2*Factorial(1) = 2* 1 = 2
          Factorial(3) = 3* Factorial(2) = 3* 2 = 6
          Factorial(4) = 4 * Factorial(3) = 4 * 6 = 24

So, you should see the pattern of factorial(n) is equal to n * factorial(n-1) where factorial(1) will provide the stop operation.

public class Factorial{
  private int x;

  public Factorial(int x){this.x = calculate(x);}

  public int calculate(int value){ return (value == 1 )? 1 : value * calculate(value-1);}
   
  public int getValue(){ return x; }
}

Paper is the key here as well.  Ask a question about the actual sequence of fibonacci numbers and write them down.

0,1,1,2,3,5,8,13,21,34,55,89 for n values 1 - 12.  You can see that we will add the previous two values together in order to find the new value.  Thus, the first two values must be considered as the stop values for the recursive process.  So, if n = 1 then return 0 and if n=2 then return 1.  Anything above the value 2 for n can be recursively calculated y previous two values. 

  Fibonacci(4) = 
  Fibonacci(1) = 0
  Fibonacci(2) = 1
  Fibonacci(3) = Fibonacci(2) + Fibonacci(1) = 0 + 1 = 1
  Fibonacci(4) = Fibonacci(3) + Fibonacci(2) = 1 + 1 = 2

Thus, the algorithm emerges.

public class Fibonacci{
    private int x;

    public Fibonacci(int x){this.x = calculate(x);}

    public int calculate(int y){return (y ==1)? 0:(y==2)? 1 : calculate(y-1)+calculate(y-2);}
   
    public int getValue(){return x;}
}

Friday, April 24, 2015

Java Polymorphism using BlueJ

Use this code to practice polymorphism and inheritance with different modifiers for a better understanding how it works in Java.



/** This simple application will help you understand polymorphism
* @version 1.0.0
* @author Zoltan Szabo
*/

public class Polymorphism{
    final static int INDEX=2;

/** application entry point to test inheritance of modifiers
* @param args as a String array for command argument input
*/

   public static void main(String[] args)   {
      SuperClass1[] obj = new SuperClass1[3];
      obj[0]=new SuperClass1();
      obj[1]=new SubClass1();
      obj[2]=new SubSubClass1();
     
      //Direct access to field values
      System.out.println("SuperClass1 public field "+obj[INDEX].x);
      //System.out.println("SuperClass1 private field "+obj[INDEX].y);
      System.out.println("SuperClass1 protected field "+obj[INDEX].z);
      System.out.println("SuperClass1 default field "+obj[INDEX].k);
  
      //Static fields from super class
      System.out.println("SuperClass1 public static field "+SuperClass1.XX);
      //System.out.println("SuperClass1 private static field "+SuperClass1.YY);
      System.out.println("SuperClass1 protected static field "+SuperClass1.ZZ);
      System.out.println("SuperClass1 default static field "+SuperClass1.KK);
  
      //Methods from super class
      System.out.println("SuperClass1 public method "+obj[INDEX].func1());
      //System.out.println("SuperClass1 private method "+obj[INDEX].func2());
      System.out.println("SuperClass1 protected method "+obj[INDEX].func3());
      System.out.println("SuperClass1 default method "+obj[INDEX].func4());
     
   }
}


/** Class that is used as the super class with different modifiers to help understand inheritance
* @version 1.0.0.0
* @author Zoltan Szabo
*/

public class SuperClass1{
    public int x=50;
    private int y=60;
    protected int z=70;
    int k=80;
   
    public static int XX=150;
    private static int YY=160;
    protected static int ZZ=170;
    static int KK=180;
   
/** Super class no-arg constuctor*/
   public SuperClass1(){
      System.out.println("This is the superclass constructor.");
   }



/** Public method in the super class 
* @return x public field from super class
*/
   public int func1(){
        return x;   
   }

/** Private method in the super class 
* @return y private field from super class
*/   private int func2(){
        return y; 
   }

/** Protected method in the super class 
* @return z protected field from super class
*/   protected int func3(){
        return z;
   }

/** Public method in the super class 
* @return k default field from super class
*/   int func4(){
        return k; 
   }
}

/**
*Class that is a child of the SuperClass1 inherits public, protected, and default attributes and methods
*@version 1.0.0
*@author Zoltan Szabo
*/

public class SubClass1 extends SuperClass1{

/** SubClass1class no-arg constuctor*/
   public SubClass1(){
      System.out.println("This is the subclass constructor.");
   }
}

//if you want to implement an interface, use this class
/**
*Class that is a child of the SubClass1 inherits public, protected, and default attributes and methods
*@version 1.0.0
*@author Zoltan Szabo
*/ public class SubSubClass1 extends SubClass1{
/** SubSubClass1 class no-arg constuctor*/
   public SubSubClass1(){
      System.out.println("This is the subsubclass constructor.");
   }
}

//*************** You can add a simple interface as well to practice implementations
/**
 * Simple interface using methods to welcome and hank users
 * @author Zoltan Szabo
 * @version 1.0.0
 */
public interface AddDetails
{
/**
* Welcome the user to your application
* @param y has no significance, only used to practice input parameters
*@return an integer value to practice return data
*/
    public int welcomeMessage(int y);
/**
* Thank the user for using your application
* @param y has no significance, only used to practice input parameters
*@return an integer value to practice return data
*/     public int thankYouMessage(int y);
}

Sunday, April 12, 2015

External JAR file in Eclipse with Javadocs

package practiceExternalJar;

import java.util.ArrayList;

import chapter07.InventoryItem;
import chapter07.Rectangle;

/**This project will help you learn how to use the external JAR file containing all the classes
* created in chapter 7.  This will also help you understand importing packages and troubleshooting
* your code with Eclipse.  Watch the accompanying video for step-by-step instructions:
* http://youtu.be/uNca-f2eP-Q
* You can run classes directly from jar files on the command line:
* i.e. java -cp jar_name.jar package.class  - java -cp Chapter07.jar varArgs.VarargsDemo4
*/


public class TestClass {

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        InventoryItem item=new InventoryItem();
        Rectangle rAngle=new Rectangle();
       
        InventoryItem[] itemArray=new InventoryItem[4];
        ArrayList<InventoryItem> itemList=new ArrayList<InventoryItem>();
        itemArray[0]=new InventoryItem();
        itemArray[0].setUnits(5);
        itemArray[0].setDescription("Test object");
       
        itemList.add(itemArray[0]);
        System.out.println(itemList.get(0).getDescription());
        System.out.println(itemList.get(0).getUnits());
        System.out.println();
    }
}

Tuesday, March 17, 2015

Sleep in Java

In order to force waiting with code execution in Java, you can put the thread to sleep for a set amount of time.  Since a process is run by a thread, we can force the thread to suspend execution and wait until the next instruction is interpreted.

In order to do this, we need to find a class that can allow us to pause a thread.  So, you look and see if there a thread class available.  It turns out that there is a Thread class.  So, you look into the class and see what methods it provides, and it turns out that it provides a sleep method.  Actually two sleep methods:


public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanos) throws InterruptedException

The second method allows you to adjust the sleep time, but in our case we do not need the method to adjust, so you can use the first and simpler method in this project.

So, you need to read the documentation of the method and understand as much about its operation as possible before using it in your own project.  In this case, we find out that it will throw an exception if another thread interrupts the current thread.  We also find out that we need to specify the time it will need to sleep in milliseconds and if we specify a negative number then it will throw an IllegalArgumentException.

Javadoc for sleep method: 
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
Parameters:
millis - the length of time to sleep in milliseconds
Throws:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

So, after you feel comfortable with the method and its capabilities, then you can implement a simple code when you iterate through the code and stop the execution of the code in every iteration by a set amount of time.  I hope, this helps you develop a methodology on how to find a class and a method for projects you'd like to implement.

public class SleepTest {
/**
* Testing of sleep() method from Thread class
* Look at the Java API to find the class and its method documentation in order to understand 
* what exception is thrown and let the calling method handle it by the throws keyword
* http://docs.oracle.com/javase/7/docs/api/

* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
String msgOut[] = {
"Java is cool, ",
"Python is cooler, ",
"but all will not make sense ",
"until you learn C++ !!!"
};

for ( int i = 0 ;  i < msgOut.length ; ) {
//Print a message from the array then go to sleep for 6 seconds
System.out.print(msgOut[i++]);
try{
Thread.sleep(-6000);  //change to a positive value to see it run properly
}
catch(IllegalArgumentException e) {
System.out.println("IllegalArgumentException was caught because "+
                       "you have specified a negative number to sleep for!!!");
System.exit(3);
}
} //end of for loop
} //end of main method
} //end of class


Another example to practice sleep.


/**
 * Write a description of class Wait here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Wait
{
     public static void main(String args[])throws InterruptedException{
    
                 System.out.println("=========== Thank You for Purchasing XYZ Application ==============");
                 for(int y=1500; y>=0;y--){
                      System.out.print("                  ======= Please Wait ===="+y+"====\r");
                      System.out.print("\\\r");
                      Thread.sleep(400);
                      System.out.print("|\r");
                      Thread.sleep(400);
                      System.out.print("/\r");
                      Thread.sleep(400);
                      System.out.print("-\r");
                      Thread.sleep(400);
                      }
          }
}

Friday, March 6, 2015

Moving to Eclipse

BlueJ is an excellent environment to get started in Java programming, but eventually you need to move to a full IDE with many more features.  More features are not helpful while learning basic concepts, but as you progress trivial tasks become annoying and feature rich programming environment can allow you to move to the next level in programming.  So, this is what this post will help you with including the accompanying video.


Basic outline of the video topics
Video reference: http://youtu.be/2yL8yCPveuk
Get Eclipse

https://eclipse.org/downloads/
https://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/luna/SR2/eclipse-java-luna-SR2-win32-x86_64.zip

Set a workspace          ( change it later if needed: File->Switch workspace->Other )

Show all Key Assist Shortcuts - Ctrl+Shift+L

Create a project
//shortcuts
New project ->                       Alt+Shift+N then J
New class ->                          Alt+Shift+N then C
Main method ->                     type main then Ctlr + Space
Println ->                                type sysout then Ctrl + Space
Toggle Comment ->               Ctrl + /        ( or Ctrl+7 )
Add block comment ->          Ctrl+Shift+/
Remove block comment ->    Ctrl+Shift+\
Add docstring ->                    Alt+Shift+J
Indent code ->                        Ctrl+A then Ctrl+I
Add libraries ->                      Ctrl+Shift+O       (use M for a single import ) 

Source->Generate ...
Create Constructors
Create getters and setters ( mutators and accessors )


Install offline documentation

Get Java Documentation
http://www.oracle.com/technetwork/java/javase/documentation
 Window --> Preferences --> Java --> "Installed JREs"

Templates can speed up your work

You can see all the templates predefined by default Window -> Preferences -> Java -> Editor -> Templates

You can also add a Template View, Window -> Show View -> Other -> Search for Templates

Create a project for a chapter exercise and import sample source code

Ugly code to fix
public class Practice06 {
private static int x;
private static int y;

private int z;
private int k;

public static void main(String[] args) {   //type main then press Ctrl + Shift then enter
System.out.println("Hello World");     //Ctrl+A then Ctrl+I to fix indentation
System.out.println("Hello Again");     //Ctrl + /  to toggle comment
File inFile=new File(args[0]);    //source
Scanner cin=new Scanner(inFile);  //System.in to get input from keyboard
File outFile=new File(args[1]);   //destination
if(outFile.exists()){
System.out.println("The output file exists, please remove it or select another file.");
System.exit(5);
}
PrintWriter cout=new PrintWriter(outFile);
while(cin.hasNext()){
cout.println(cin.nextLine());
}//end of while
cin.close();
cout.close();
} // end of main
}  //end of class
 


Code discussed in the video

import java.io.File;          //Ctrl+Shift+O
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * Practice  COSC 1437 class project
 * @author Zoltan
 * @version 1.0.0
 */

public class Practice05 {
    private static int x;
    private static int y;
  
   
    /**
     * @param z
     * @param k
     */

    public Practice05(int z, int k) {
        super();
        this.z = z;
        this.k = k;
    }

    /**
     * @param z
     */

    public Practice05(int z) {
        super();
        this.z = z;
    }

    /**
     *
     */

    public Practice05() {
        super();
    }

    /**
     * @return
     */

    public static int getX() {
        return x;
    }

    /**
     * @param x
     */

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

    /**
     * @return
     */

    public static int getY() {
        return y;
    }

    /**
     * @param z
     */

    public void setZ(int z) {
        this.z = z;
    }

    private int z;
    private int k;
   
    /**
     * Entry point to my application  //docstring Alt+Shift+J
     * @param args as a String array
     * @throws FileNotFoundException
     */

    public static void main(String[] args) throws FileNotFoundException {   //type main then press Ctrl + Shift then enter
        System.out.println("Hello World");     //Ctrl+A then Ctrl+I to fix indentation
        System.out.println("Hello Again");     //Ctrl + /  to toggle comment

        File inFile=new File(args[0]);    //source
        Scanner cin=new Scanner(inFile);  //System.in to get input from keyboard

        File outFile=new File(args[1]);   //destination
        if(outFile.exists()){
            System.out.println("The output file exists, please remove it or select another file.");
            System.exit(2015);
        }
        PrintWriter cout=new PrintWriter(outFile);
        while(cin.hasNext()){
            cout.println(cin.nextLine());

        }//end of while

        cin.close();
        cout.close();

    } // end of main

//end of class