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

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;
}
}
 

Friday, February 27, 2015

Access Modifiers


Use the code below to practice the access modifiers effects on fields and methods.  Save this code  as ClassA.

Copy HelperA code three times and rename two of the copies to HelperB and HelperC. ( don't forget to adjust the name of the constructors )
Add package package1; to all three newly created classes.

Make two more classes HelperD and HelperE by copying this code again and adding package package2; to the beginning of the classes.

That way, you will have three classes in one package and two classes in another package, so you can "play" with access to fields and methods.

Try to compile the classes and see the effects.  As you are getting error messages, just comment out the statement that causes the error message.  Make a note of the error message, comment no access, and continue until you have no more compile errors. 

As you are making modification to classes, keep track of the errors and verify this table's values with fields and methods.  You can also extend this table with other test values if needed.


public class ClassA {
   
    private int value;
    public static int static_ident;
    public static final String  CONSTANT= "STATIC CONSTANT STRING";

    public ClassA(int value ){  value=value; static_ident=2015; }  //value is a shadow, avoid it

    public int getValue(){return value;}
   
    public static int getStatValue(){return static_ident;}   //can not use this for static
   
    public static void main(String args[]) {

        ClassA me=new ClassA(20);
        String myName=new String("Richland College");
       
        System.out.println("Hello My Non-Static Value!!!"+me.getValue());
        System.out.println("Hello My Static Method!!!"+me.getStatValue());
        System.out.println("Hello Constant Field!!!"+CONSTANT);   //can not refer to it as this.CONSTANT
       
        HelperA helper=new HelperA();
       
        //System.out.println("Hello Helper Private Method!!!"+helper.getPriName());  //no access
        System.out.println("Hello Helper Public Method!!!"+helper.getPubName());
        System.out.println("Hello Helper No Method!!!"+helper.getNoName());
        System.out.println("Hello Helper Protected Method!!!"+helper.getProName());
       
        //System.out.println("Hello Helper Private Field!!!"+helper.pri_name);  //no access
        System.out.println("Hello Helper Public Field!!!"+helper.pro_name);
        System.out.println("Hello Helper No Field!!!"+helper.no_name);
        System.out.println("Hello Helper Protected Field!!!"+helper.pub_name);
    }

}

class HelperA{
    private String pri_name;
    public String pub_name;
    String no_name;
    protected String pro_name;
   
    public HelperA(){
       pri_name="pri_Anonymous";
       pro_name="pro_Anonymous";
       no_name="no_Anonymous";
       pub_name="pub_Anonymous";
    }
   
    private String getPriName(){ return pri_name; }
   
    public String getPubName(){ return pub_name; }
   
    String getNoName(){  return no_name;  }
   
    protected String getProName(){ return pro_name; }
}

Thursday, February 26, 2015

Coder Body Types

Which one are you?

Programming can be frustrating in many cases, but those starting out on learning a language should not have a reason to be frustrated if the basics are established correctly.  Creating a project should not start with opening the IDE and starting to program.  the problem should be understood and well researched before a meaningful UML, pseudo code, and/or a flowchart can be created to guide the development process.  Only after spending enough time on the design and algorithm should the coding begin.  If the correct IDE and language is selected, the coding portion should take the least amount of time.  that requires for someone to know the syntax intricacies of the language, but a good design will take much of the frustration out of coding.  The last and most important stage is the testing phase that can reveal all the semantic errors since the compiler will not be helpful in identifying those type of logical errors.  A good programmer will spend enough time on testing the code and test all the scenarios the application will face until a high level of certainty is achieved of the application reliability.  

So, as a beginning programmer, you are most likely spend way too much time on your coding and implementation because you have not spent enough time on the design of your project.  Even if you spend enough time on researching and taking courses that help you understand the math behind the problems and you can design a great algorithm, you might not see the value of through testing of the application and might introduce many logical errors into the application since implementing a design can be tricky.

This simple example could cause many hours of troubleshooting and frustration: 

float fahrenheit=82;
float celsius = ( fahrenheit -32 ) * ( 5 / 9 );

This is simple code can be fixed by ( 5 / 9.0 ) to turn an integer division into a mixed division and have a real number as a result instead of an integer that would always be zero.  This kind of mistake can be caused by a good design and bad implementation, but proper testing methodology can reveal this mistake.  Testing should be done with at least 32 and 212 for an easy to see known value result of 0 and 100.  Other values like a positive value and a negative value could also be used to test the proper sign of the results.  

So, understand the syntax of the language and the intricacies of computer operations to reduce time spend on coding and increase the time spent on design and testing to ensure the proper solution. 

                   Advanced                                     Beginner                                           Intermediate


Tuesday, February 24, 2015

Hash Calculator

Look at this code and see if you guys like to make this code into a more complex project. Always talk about a way to test if your code works properly and testing methodology before implementing your code. Testing is as important as coding.

import java.util.Scanner;
import java.security.MessageDigest;
import javax.swing.JOptionPane;
import java.io.UnsupportedEncodingException;


/**
* Application to practice creating a message digest with specifying algorithm
* @author Zoltan
* @version 1.0.0
*
*/
public class Driver {

/**
* Entry point to the application
* @param args String array that is not used in this code
*/
public static void main(String[] args) {

//variable declarations
byte[] messageBytes;
String password;
MessageDigest mDigest;
byte[] theHash;

//Let user specify the clear text password by entering a string
password = JOptionPane.showInputDialog("Please enter your password");
JOptionPane.showMessageDialog(null, "Your password was: "+password);

//Convert the entered password string to a byte array in UTF-8 encoding
//The encoding should never throw an exception in this case, but it is required for this method.
try{
      messageBytes= password.getBytes("UTF-8");
      }
catch (UnsupportedEncodingException e) {
                   throw new AssertionError("UTF-8 is unknown");
      }

//Generate the message digest for the clear text of byte array
try{
      //Lookup the available algorithms and adjust the code to be dynamic of fix
      // http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#MessageDigest
       mDigest = MessageDigest.getInstance("MD5");
       theHash = mDigest.digest(messageBytes);

       //Convert the byte array to Hex values for display 
       StringBuffer sBuffer = new StringBuffer();
      
       for (int i = 0; i < theHash.length; i++) {
             sBuffer.append(Integer.toString((theHash[i] & 0xff) + 0x100, 16).substring(1));
            }

       // Verify the results on-line with a simple string
       // like "password" http://www.miraclesalad.com/webtools/md5.php

       JOptionPane.showMessageDialog(null, "Your password hash is: "+sBuffer);
}
catch (java.security.NoSuchAlgorithmException e) { }

     }// end of main method
}//end of Driver class

Sunday, February 22, 2015

Greenfoot game and Javadoc

This is the code for the game created for the class learning about the value of documentation.
Watch the video to understand and appreciate the learning process of this code.
https://www.youtube.com/watch?v=kOnvLnmbeno


public class myWorld extends World
{
public myWorld(){
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 400, 1,false);
getBackground().drawRect(300, 200, 100, 100);
getBackground().setColor(java.awt.Color.CYAN);
getBackground().fillRect(Greenfoot.getRandomNumber(550),Greenfoot.getRandomNumber(150),50,50);

prepare();
}

private void prepare(){
myDot mydot = new myDot();
addObject(mydot, 109, 96);
}
}

import greenfoot.*;

public class myDot extends Actor{
public void act() {
setLocation(getX()+5,getY()+5);
if(isAtEdge()){
gameOver lost=new gameOver();
getWorld().addObject(lost,getWorld().getWidth()/2,getWorld().getHeight()/2);
Greenfoot.stop();
}
if(Greenfoot.isKeyDown("up")){
setLocation(getX(),getY()-Greenfoot.getRandomNumber(25));
}
java.awt.Color isOnTop = getWorld().getBackground().getColorAt(getX(),getY());

if(isOnTop.equals(java.awt.Color.CYAN)){
//System.out.println("I'm over it!!!");
UgotIt won=new UgotIt();
getWorld().addObject(won,getWorld().getWidth()/2,getWorld().getHeight()/2);
Greenfoot.stop();
}
}
}

public class gameOver extends Actor{
public void act() {
// Add your action code here.
}
}

public class UgotIt extends Actor{
public void act() {
// Add your action code here.
}
}

Saturday, January 24, 2015

Documentation and Comments

Many people starting out in programming thinks that documentation and commenting is a waste of time and it does make them better programmers.  It might be that documentation does not make a better program, but the quality of code can also be measured by its comments.  Just like science is not a science without documented measurements, code is not part of computer science if it is not documented.  

As more programming languages support docstrings, that feature of the language actually makes better programmers right from the start.  Java is one of those languages that is easy to learn, but its ability to support docstrings is not focused on in the early stage of learning.  

Java is also a great language to help those new to programming learn documentation of existing libraries of classes.  The main difference between a novice and an expert is that an expert know how to get help when needed in a fast and efficient way.  Thus, education could focus on not just the syntax, but focusing on how to find answers when questions arise.  That would help novice graduates overcome confusions faster and focus on real problem solving issues instead.  

Computer Science is also evolved to many languages and can not rely on a single language that is considered the latest "fad".  It is the combination of languages in order to solve problems by picking the right "tool".

Thus, you need to learn about many languages and collect your notes in a way that you can use regardless of the language you will use, but helps you with the required syntax.

This flowchart can be one of the ways you can map simple concepts and document each language.


  

Eclipse Shortcuts

Eclipse IDE is an amazing environment to help you learn many languages in one simple to install and use environment.  You can use it to learn Java, C++, and Python without learning IDE for each of those languages.  That way, you can focus on the actual language instead of wasting time learning another IDE.

Eclipse has man shortcuts that can help you make your programming experience much more fun by providing shortcuts for repeated tasks.

Auto-generate constructor
Auto generate setters and getters
Project->Generate javadoc
sysout + Ctrl + Space


Ctrl + i - indent selection
Ctrl+Shift+o - import required libraries
Ctrl+D - delete line
Alt+Shift+R - rename all occurrence of an identifier
Ctrl+F11 - run the code


Others

Alt+up or down  - Move a line of code up or down
main + Ctrl + Space  - Create main method signature
Ctrl+D  - Show hierarchy of a class
Ctrl+/ - comment the source code line
Ctrl+L - jump to line number
Ctrl+q  - last edit location
Ctrl+ o - outline of class

Short video summarizing most of the features mentioned in this post.
https://www.youtube.com/watch?v=7ESqUgkzke4

Wednesday, January 14, 2015

ReadyNAS 104 and iSCSI

There are many talks about cloud storage and storing files remotely as a way to protect data from loss.  While it is a great way to use free services for this purpose, you might also need to think about learning about this technology as a learning environment.  It does not matter if you are an information technology, information assurance, digital forensics, cybersecurity, or computer science student, you will need an infrastructure where you can experiment and learn on your own.  Hardware prices and open source operating systems make the setup of this environment easy and cheap.

If you are in computer science and try to learn about programming, you might find it easier to learn about network based programming by setting up a web server and experimenting with HTML and JavaScript as a start.

It seems like every application that is written these days are based on web services or use web services as its interface.  Thus, it is in your interest to learn about network based programs and program execution.  You will also need to think about safeguarding the code you write and ensuring its availability as you are progressing with your studies. So, you might need to learn about server management and file sharing.

One of the lesser known file sharing technologies is iSCSI ( Internet Small Computer System Interface, an Internet Protocol (IP)-based storage networking standard ).  It typically use TCP ports 860 and 3260 and provides authentication for secure sessions.  It is based on the Target ( server ) and the iSCSI Initiator ( client ) model that is built into Microsoft Windows 7 and above or can be freely installed on XP machines for iSCSI support.

There is not much "talk" about this technology, so I wanted to bring this technology to light for those of you interested setting up a home based network environment.

Watch video on how to setup and use a ReadyNAS based system.
http://youtu.be/Ag3tfc2VSUA

 

Getting started with Java

Java syntax and API is a simple to learn and use.
Java is object-oriented where each object can perform one or more discrete tasks and contains all the data needed to perform the task.
Java is distributed, you can send data across the net easily.
Java is robust, so programs run correctly and do not break when the unexpected happens.
Java is secure by limiting access of programs to your resources and files on your computer.
Java is architecture-neutral and portable by writing the code in one computer and running the code on another machine with another hardware configuration.
Java byte code is interpreted by a virtual machine not directly by the operating system.
Java is multithreaded as the programs share data and instructions.
Java is dynamic by calling upon resources as needed.

In order to learn this language, I recommend this path of action:


  1. Know how computers work 
    1.  - CPU, ALU, RAM, Thread, Process, Memory Address, and Interrupts
  2. Know how CPU instructions carried out
    1. - Assembly language instructions ( mov, jmp, cmp, add, ... )
  3. Know how file systems store data and how to manage your files in folders
  4. Know basic command line utilities ( dir, mkdir, rmdir, copy, set, echo, ... )
  5. Know how to get help from the local system or utilities and how to read the help documentation
  6. Know about path and other environmental variables
  7. Understand basic automation commands in the terminal
    1.  - i.e. for %i in ( 1 2 3 4 ) do echo Hello World %i
  8. Understand basic script execution and syntax
    1. - i.e. hello.bat -> for %%i in ( 1 2 3 4 ) do echo Hello World %%i
  9. Understand difference between JRE and JDK 
  10. Install and run ( javac, java ) simple Java program written in notepad.exe  ( see below )
  11. Learn C++ function and structure concepts 
  12. Understand the importance of documentation ( javadoc )
  13. Understand the importance of flowcharts, pseudo code, UML
  14. Create simple algorithms based on what you know 
    1. i.e. Calculate the are of a circle 
      1. create a table with columns radius, diameter, PI, area
      2. enter values into radius column
      3. calculate diameter and keep in mind the function ( d= 2 * r )
      4. write PI for each row ( this will need to be accessed by each row, so it is static )
      5. calculate the are ( a = r * r * PI )
      6. analyze the results
        1. each column with changing values without formula will be variable 
        2. each formula columns will be function/method 
        3. each entry that does not change will be final and static for all to access 
        4. value on the left side of the equation will be the return value for the method
        5. think about the documentation hat would help another person learn about your code
      7. write the code and look for syntax errors
        1. determine proper data types for identifiers
      8. identify unneeded code 
        1. diameter should be removed or changed to hold r*r as a sub-calculation since it can help with troubleshooting, but you can ignore 
      9. think about input validation to ensure positive radius values
        1. you can create another method to return an absolute value of radius before calculation of area
      10. enter the values from your table and test if you get the same results from your code
  15. Use Raptor to create code from flowchart
  16. Always generate javadoc of your own code and understand how to read it
  17. Use BlueJ to visualize objects and inheritance
  18. Use Greenfoot to understand GUI concepts and create simple games
  19. Move to a full featured Integrated Development Environment ( IDE ) like Eclipse
  20. Understand how to use the debugger to monitor values in your code at different stages of processing
  21. Make mistakes and learn from the error messages
  22. Add features to code you wrote and understand as you learn more about a language 
  23. Don't be afraid to experiment 


 /** Student Class establishes the student id, name and grade
  *  @author Richland Teacher
  *  @version 2015
 */
 public class hello
 {
     private final String studentName;
     int value;
     public static int year;
     /**
      * This is a method that will take two parameters and will set a single field in the object
      * @param parameterOne imaginary first name as a String
      * @param parameterTwo imaginary last name as a String
      */
//Constructor for the hello class
public hello( String parameterOne, String parameterTwo ){
          studentName=parameterOne+parameterTwo;
          value=100;
          year=1900;
}
    // Main method
     public static void main(String[] args)
     {
         String name="My name is: ";
         System.out.println("Hello, "+name + args[0]);
         hello testing = new hello("firstname","lastname");
         System.out.println("Hello "+testing.value+"  "+year);
     }
  }// End of  class

Wednesday, January 7, 2015

Problem to Execution Methodology

Computer Science does not start with coding, but preparation and analysis in order to solve a problem at hand. That process requires many years of preparation and logical approach to solve problems. Thus, computer science is not as dependent on the programming language as most people think it is. Your first question about computer science should not be, "What language I should learn?", but how do I learn to solve mathematical problems. Problem solution starts with simplification, pattern recognition, and strong math background to create an algorithm that can solve the problem at hand in a finite amount of time and in a reliable way. Lately, we might also add the consideration of "securely" in order to solve problems in a way that is securely controlled.




In many cases, you will need to learn how to compile your code, but the Graphical User Interface ( GUI ) based IDE environments can divert your attention from how the process actually works.  I have created a video to help you understand the process of compiling code.  The video will also show you how to create libraries and DLLs and compile these static and dynamic libraries into your code.

http://youtu.be/7Gt5FJpEQvA