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

Tuesday, March 3, 2015

Random numbers

Science is about measurements and understanding complex problems.  Understanding by inductive reasoning requires reliable data points that can be analyzed for a pattern to draw conclusion.

True random numbers are very hard to create, so we can test how Java creates random numbers and see if they are really random.

This is a sample code to get you started thinking about computer science as a scientist.  Run this code many times and chart the results to see the distribution of the numbers generated when you roll a dice in a Java application.  See if you can identify numbers that are more likely to show up than others and how consistently can you predict the most frequently occurring numbers.

import java.util.Scanner; // Needed for the Scanner class
import java.util.Random;

/**
 * Testing the random number generators in Java
 * @author Zoltan Szabo
 * @version 1.0.0
 */

public class RamdomTest
{
/**
 * Entry point to RamdomTest application
 * @param args as String array
 */
   public static void main(String[] args)
   {
      String name=new String();         // The user's name
      Random values=new Random(System.currentTimeMillis());  //Ramdom class allows to enter a seed value, you should try to set a single value vs. a dynamic value like the current time in this case
      int rand=abs(values.nextInt()%6);
      int x=0,zero=0, one=0,two=0,three=0,four=0,five=0;
      while(x++<1000000){
          switch(rand){
              case 0: zero++;break;
              case 1:one++;break;
              case 2:two++;break;
              case 3:three++;break;
              case 4:four++;break;
              case 5:five++;break;
            }
            rand=abs(values.nextInt()%6);
        }
     
     System.out.println(zero+"  " + one + "  " + two + "  " + three + "  " + four + "   " + five + " With current time as seed.  ") ;
 
     Random values2=new Random(5);  //constant seed value
     rand=abs(values2.nextInt()%6);
   
     x=0;
     x=0;zero=0; one=0;two=0;three=0;four=0;five=0;
           while(x++<1000000){
          switch(rand){
              case 0: zero++;break;
              case 1:one++;break;
              case 2:two++;break;
              case 3:three++;break;
              case 4:four++;break;
              case 5:five++;break;
            }
            rand=abs(values.nextInt()%6);
        }
     
     System.out.println(zero +"  " + one + "  " + two + "  " + three + "  " + four + "   " + five + " With constant value as seed.  " ) ;
 
     Random values3=new Random();  //no seed
     rand=abs(values3.nextInt()%6);
   
     x=0;
     x=0;zero=0; one=0;two=0;three=0;four=0;five=0;
           while(x++<1000000){
          switch(rand){
              case 0: zero++;break;
              case 1:one++;break;
              case 2:two++;break;
              case 3:three++;break;
              case 4:four++;break;
              case 5:five++;break;
            }
            rand=abs(values.nextInt()%6);
        }
     
     System.out.println(zero +"  " + one + "  " + two + "  " + three + "  " + four + "   " + five + " With no seed.  " ) ;
 
     double values_math;
     rand=(int)(Math.random()*10000)%6;
     x=0;
     x=0;zero=0; one=0;two=0;three=0;four=0;five=0;
       while(x++<1000000){
          switch(rand){
              case 0: zero++;break;
              case 1:one++;break;
              case 2:two++;break;
              case 3:three++;break;
              case 4:four++;break;
              case 5:five++;break;
            }
           rand=(int)(Math.random()*10000)%6;
        }
        System.out.println(zero +"  " + one + "  " + two + "  " + three + "  " + four + "   " + five + " With                   Math.random() method  ") ;
    }

private static int abs(int v){
    return (v<=0)?-v:v;
}
}