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

No comments:

Post a Comment