Wednesday, November 2, 2016

UML in BlueJ and Eclipse

Unified Modeling Language ( UML ) is the best way to design an application and to analyze an object oriented code.

Taking a code and easily turn it into a UML can be done with an IDE, but there are extensions for IDEs that do not support UML generation by default.  BlueJ has two extensions that can be used for this purpose.

BlueJ UML extensions video if you need it
https://youtu.be/e5h15mTvEP4

Copy the jar files into folder <BLUEJ_HOME>\lib\extensions

Class Card - A Better UML Extension - http://klassenkarte.steinhuber.de/
Con: No datatypes for attributes and parameters
Pro: Shows attributes

UML Extensionhttp://www.bluej.org/extensions/extensions.html 

Con: No attributes listed
Pro: Parameter and return value data types


 After adding the extensions, they will be available by right-clicking on the class you need to see its UML.


You can see the difference between the two extensions and decides witch one works for you.


At the end, you'll see that Eclipse does a much better job showing the UML based outline of the class and if you don't really need pretty graphics based UML, it will be the most complete UML with the least effort.



Greetings from a JAR

A typical simple application looks like this from a first year student taking Java for the first time.  the code works, but it is not college level, detail oriented, and user friendly application.  the beauty of modern programming languages is the same as the beauty of modern technology, it is easily adoptable and user friendly.  Java is an easy language to pick up and learn because of its documentation, so don't ignore what makes Java strong.

Modern applications are also user friendly and engaging, so make sure you create your own brand by being consistent in your coding and be nice to your users.  Give users a basic information about yourself and about the application, but most importantly welcome the users like thy are your guests.  there are many great applications that are out there, but you have to be unique in your application approach and don't let a user just leave after running your program.  Thank them for using your program and either tell them about your other applications, give them incentives to come back, or at least send them to your website.

public class SampleApp {
public static void main(String[] args) {
System.out.println("The number 10 raised to the power of 3 is: " + java.lang.Math.pow(10,3));    
System.out.println("Hello World");
}
}

Videos to use Greetings.jar in BlueJ and Eclipse

Greetings JAR BlueJ
https://youtu.be/F0-ClRhUZA4

Greetings JAR Eclipse
https://youtu.be/qK88J11N0VE


Greetings.jar file Download

So, that simple application can be embellished to make it fit to be called Java code and the branding can be done easily with custom classes.  Thus, in this project you'll learn how to use someone else's jar packaged classes in BlueJ and in Eclipse.  The classes are simple enough, so you can learn how to handle import statements, read documentations, and the concept of static methods.

All these simple suggestions will make you a better programmer and a consistent professional!

import rlc.zoltan.COSC.Welcome;
/**
 * Description
 * @author  Name
 * @version 1.0.0
 */
public class SampleApp {
    /**
     * Description
     * @param args string array from the command line
     * @return void
     * @throws Nothing is implemented
     */
    public static void main(java.lang.String[] args)     {
     //Let your users know that you appreciate them for choosing to use our application
     Welcome wmsg=new Welcome("Welcome to my course. I hope you'll enjoy it.");
     rlc.zoltan.COSC.MyCourse.InfoI();
     java.lang.System.out.println(wmsg);
 
    java.lang.System.out.println("The number 10 raised to the power of 3 is: " + java.lang.Math.pow(10,3));        java.lang.System.out.println("Hello World");
 
    //Keep your users engaged as they leave
    rlc.zoltan.COSC.Appreciate thanks=new rlc.zoltan.COSC.Appreciate();
    java.lang.System.out.println(thanks);
    }
}

Let me know if you need a copy of the Greetings.jar file that this example code was based on.  

Saturday, October 15, 2016

Base UML / Structured Logic of methods

Unified Modeling Language ( UML ) is a great way to visualize the relationships and interaction designs of objects, but it is not helpful for the structured design of the methods.  Thus, in this standard, we bring both together where we start with the UML and then add the structured logic for each one of the methods for clear communication of the design ( schema ) to the implementer ( coders ) like the architect communicates his/her design to the journeymen.

Remember design of the algorithm is our way of communication not a necessary evil or extra work.  Remember design is the third step before we start to program without it, it is not program design, just coding.  Reference for the programming life cycle  -  http://intro2cs-java.blogspot.com/2015/01/problem-to-execution-methodology.html


Friday, October 14, 2016

While Loop Summary Exercise

Run this summary code and you will know everything you need to know about while loop structures in Java.  Make sure to go to Java API and read about the classes and/or methods that causes questions or confusion.  The API documentation is not just the bet source, but the best practice you can perfect for a long term success. 

import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;          //not covered until chapter 10
/**
 * This class summarizes all structures related to while loops including file IO with validation
 * @author Zoltan Szabo
 * @version 1.0.0
 */
public class WhileSummary
{
    /**
     * Entry point to application
     * @param args string array from the commandline sent to application
     * @return none
     */
public static void main(String[] args)throws Exception
{
      int value = 5;
  
      //File IO validation without try/catch block
      File inFile=new File("input.txt");   //source file name
      File outFile=new File("output.txt"); //destination file name
     
      if (!inFile.exists()){           //Checks if the file name exists
         System.out.println("Source file " + inFile + " does not exists.");
         System.exit(4);               // Exit the program.
      }
      Scanner input = new Scanner(inFile);  //Look at the Scanner constructor documentation to find what it throws when constructed with File parameter
          
      if (outFile.exists()){           //Checks if the file name already exists, look up the method docs
         System.out.println("The destination file " + outFile + " already exists.");
         System.exit(5);            // Exit the program. Look up the method docs
      }
      PrintWriter output = new PrintWriter(outFile);
     
      //while with counter control - if you know the number of iteration needed
      int counter=0;       //priming value
      while(counter < 5 ){                       //decision
          System.out.println("The value is: "+counter);
          counter++;                  //update                
      }
     
      //while with flag control - when the object controlling the loop has a property to test for
      while(input.hasNext()){                    //read input file until it reaches the end of file, method docs
          //System.out.println(input.nextLine());
          output.println(input.nextLine());           //Loop up the method docs
      }
     
      //while with sentinel control - when you want to allow user interaction or predefined value to end the iteration
      Scanner keyboard=new Scanner(System.in);
      char answer='y';                                             //priming value
      while(answer != 'n' ){                                       //decision
          System.out.println("Your answer is: "+answer);
          System.out.println("Enter it again (y/n): ");            //prompt
          String temp=keyboard.nextLine();                      
          answer = Character.toLowerCase(temp.charAt(0));          //update
      }
     
      //for loop - simplified while loop ternary format
      for(int count=0;counter < 5;count++ ){                       //priming value;decision;update
          System.out.println("The value is: "+count);
      }
      //continue / break usage in for loops
      for(int i=0;i<100;i++){
         if(i%2==0)
            continue;
         System.out.println(i);           //print only odd numbers
         if(i==55)
            break;                        //quit the loop at 55
      }
    
      //enhanced for loop
      //processing array the traditional way if index values need to be adjusted
      int array[]={1,2,3,4,5,6,7,8};
      for(int i=0;i<array.length;i+=2){
          System.out.println("The traditional way is: "+array[i]);
      }
      //if all values must be processed from start to finish
      for(int temp:array){
          System.out.println("The value is: "+temp*10);
      }
       
      //do while - when you want to have the loop run at least once - only post test loop
      answer='n';       //priming value
      do{
          System.out.println("Your answer is: "+answer);
          System.out.println("Enter it again (y/n): ");       //prompt
          String temp=keyboard.nextLine();                      
          answer = Character.toLowerCase(temp.charAt(0));     //update
      }while(answer != 'n' );                                 //decision
      //nested for loop - inter-dependent loops from fastest ( inner ) to slowest ( outer ) fastest loops
      //Simulate the clock.
      for (int hours = 0; hours <= 12; hours++)               //slowest loop
      {
          for (int minutes = 0; minutes <= 59; minutes++)     //slower loop
          {
             for (int seconds = 0; seconds <= 59; seconds++)  //fastest loop
             {
                System.out.printf("%02d:%02d:%02d", hours, minutes, seconds);
                System.out.printf((hours>=12)?"PM\r":"AM\r");
                Thread.sleep(1000);
             }
          }
      }
      //Deal with negative numbers in loops using private method and binary AND
      byte count=0;
      while(toUnsigned(count)>=0){
         System.out.println(toUnsigned(count));
         Thread.sleep(50);
         count++;
        }
     //System.out.println(count);
      input.close();         //Don't forget to close files
      output.close();
  }
 
private static int toUnsigned(byte n){
      return n&0x000000FF;
   }
}

Sunday, May 1, 2016

Modular Programming or Just the Way You Think?

Most people interested in any scientific discipline are visual learners and INTJ ( stands for Introverted, iNtuition, Thinking, Judging ) personality types.  It is hard to accept new concepts like design before code or test when you are done, but when they realize that every decision they ever made was following a rigid flowchart and they enjoy the pre-designed flow in decision making, the program design concepts become one of the most liked tools.

Modular coding is the same concept as we divide and conquer complex situations.  Each main concept is implemented as a module where the modules are simple, focused, and improved individually as needed.  The modules can be applied to different situations for a quicker solution even if minor adjustments need to be made.

Let's see how to us this concept in getting through college.  Is it helpful?  Do you see the value of it? Did you just realize that you were confused in science classes because no one taught you this way of thinking?  You're welcome :-)



Programmer Training vs. Education

No matter how you think about programming desired outcomes, there is a huge difference between those learned programming from watching YouTube videos and those learned the basics in a classroom.  I would say, there is also a huge difference between those learned programming in a face-to-face classroom vs. on-line classroom. 

There is no substitute of human interaction, real time Q&A, and working with others who are struggling with the same concepts. 

There is a difference between how corporations view education and the level of details they need from programmers.  The basic concept in education is not to cater to current needs of the corporate environment, but to provide and complete skill set for the educated workforce to encourage innovation and adaptability to the ever changing corporate landscape. 

Training on the other hand, provides the most current technical aspects of the latest technology, but it is useless unless there is a strong foundation behind a person.  Thus, a strong educational baseline and continuing training can provide a lifetime learner who has the latest skills, able to innovate, and feels resilient even in challenging environments.

Here is a video of different requirements by the different environments for the same problem.

https://www.youtube.com/watch?v=CqLhME92guI

As far as education is concerned, it is the institution's responsibility to provide the "worst case scenario" where programming is the structured process of development by well defined stages.

Understand the problem - Interview, understand the business needs
Analyze the gathered data - Select relevant nouns and verbs related to the problem that will eventually form variables, constants, functions, and methods
Design the best fit solution - Plan the algorithm based on learned data structures and tested solutions by drawing UML for objects and pseudo code or flow charts for each method or function including all validation plans
Code the approved design - Select the language best fit the problem at hand, space requirements, hardware availability, data size, and speed requirements.  Focus on structured code structure
Compile the code - Only solve small sections of the code at a time in a modular or object oriented fashion using 3rd party libraries that are well tested and written by well respected vendors
Link the objects into an executable - Link the code to the hardware that will be used to run the final product
Load the executable - See if it runs and see if the operating system logs any messages.  Test what access privileges the application needs in order to execute properly
Test the final product - Establish proper test values ( preferably automated script ) and test all possible flowchart identified paths with values testing inside and outside ranges, end-values, and most importantly all possible wrong values to test validation rules

Are these all used in a corporate environment? Of course not, but even an architect needs to learn how to write and read a blue print.  It is the proper way of doing it, but in a corporate environment this type of programming process is too expensive and time consuming to be used all the time.  Education does not look at profit margins and deadline requirements; just proper development of reliable code.

Let see an example design and implemented code:


So, what kind of feedback you will get if you code like this?  Most likely not very positive responses from other coders, but praises from those who will actually be responsible hiring you.  So, do not give in to peer pressure, it is in your best interest to learn the hard way and adopt to the situations as needed.  






Saturday, April 30, 2016

ListIterator in Java as It Relates to File Recovery


Understanding lists and especially linked lists are not just essential for a flexible array operations, but also key concept in data structures.  The list iterator class is a useful class to traverse the list contents in an easy an convenient way.

I can just imagine Bill Gates learning about data structures and linked lists in college and thinking to himself that this kind of structure can be used to catalog file chunks and keep all of the chunks in a simple object array. 

In the technical fields, we can find linked lists in the implementation of file systems like File Allocation Table ( FAT ).  The Directory entry is an array of pointers pointing to the first node in the list of nodes connecting all clusters that belong to a single file.  The end of the file is marked by setting of the next pointer to null or FFFF in a case of FAT16.  Looking at the FAT table, you would expect to see these values in little endian format, 2001 2101 FFFF written at cluster numbers 287, 288,289 respectively.


In this case, you can see the file named _ESTFIL.TXT is the deleted file that we'll try to reconstruct.  We know its size is 1443 bytes and the start of the linked list that contains the file contents is starting at cluster 287.  The underscore character is replaced by the σ ( sigma or 0xE5 in Base-16 value ) character when the file is deleted.  Since we know the file size and since this is a floppy drive with cluster size of 1 or 512 bytes, we can easily calculate that it will take 3 clusters to store this file, thus 3 clusters need to be located in order to recover it.  Thus, we'll have 512bytes in the first cluster, 512 bytes in the second cluster, and 419 bytes in the third cluster.  As you can see below, ( look at the yellow numbers only ) 288,289, and <EOF> are highlighted. The number of 288 is on top of cluster 287 where our file started.  So, 287 is the location of the cluster number and the number is the next pointer that points to cluster 288.  At cluster number 288, the value is 289 meaning that cluster 288 is pointing to 289.  As you can see, cluster value 289 ( see image below ) is holding the value <EOF> designating the end of the file.
java.util.LinkedList -  is a doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

java.util.List - An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

java.util.ListIterator - An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.

java.util.ArrayList - Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.

Simplified UML diagram of the example code discussed in this post.



import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.LinkedList;


public class CarDemo{
  public static void main(String args[]){
    ListIterator<Car> litr = null;
    List<Car> cars = new ArrayList<Car>();
    cars.add(new Car("Toyota","Supra"));
    cars.add(new Car("Honda","Accord"));
    cars.add(new Car("Mazda","MPV"));
    cars.add(new Car("Porsche","Carrera"));
    cars.add(new Car("BMW","M3"));

   
    LinkedList<Car> linkedlist = new LinkedList<Car>();

         linkedlist.add(new Car("Toyota","Supra"));
         linkedlist.add(new Car("Honda","Accord"));
         linkedlist.add(new Car("Mazda","MPV"));
         linkedlist.add(new Car("Porsche","Carrera"));
         linkedlist.add(new Car("BMW","M3"));

        
    litr=cars.listIterator();

    while (litr.hasNext()) { //all of this is done on a single node
           //set a new model for the first node, next() will advance
           litr.next().setModel("Volkswagen");
          //go back to the first node and get its node and get its model, sets the position back one node
          System.out.println(litr.previous().getModel()); 
         //go forward again to the first node and get its make
         System.out.println(litr.next().getMake());
         litr.previous();      //this will cause us to be in an infinite loop
    }
  }
}


public class Car{
    private String make;
    private String model;

    public Car() {
        make="";
        model="";

    }
    public Car(String ma,String mo) {
        make=ma;
        model=mo;

    }
    public String getMake()    {return make;    }
    public String getModel()    {return model;    }
    public void setMake(String ma)    { make=ma;    }
    public void setModel(String mo)    { model=mo;    }

}

The code above will create an array of file objects of Car.


The linked list is structured very differently and it is much closer structure to the file system example we started this discussion.  Each car object added to the list has its next and prev pointers.

         linkedlist.add(new Car("Toyota","Supra"))       //first node, prev=null
         linkedlist.add(new Car("Honda","Accord"))
         linkedlist.add(new Car("Mazda","MPV"))
         linkedlist.add(new Car("Porsche","Carrera"))
         linkedlist.add(new Car("BMW","M3"))             
//last node, next=null


Object structure pointing to the first node of the linked list.


As you can see below the last pointer's next pointer is null indicating the last node and the end of the linked list.