Java Structures Exercises

  < Previous  Next >
  1. Draw a flowchart that represents each of the parts of the following Java code:
    int counter = 0;
    System.out.println( "Before the loop" );
    while( counter < 3 ){
        System.out.println( counter );
        ++counter;
    }
    System.out.println( "After the loop" );
  2. Draw a flowchart that represents each of the parts of the following Java code:
    System.out.println( "Before the loop" );
    for( int counter = 0; counter < 3; ++counter){
        System.out.println( counter );
    }
    System.out.println( "After the loop" );
  3. Draw a flowchart that represents each of the parts of the following Java code:
    int counter = 0;
    System.out.println( "Before the loop" );
    do{
        System.out.println( counter );
        ++counter;
    }while( counter < 3 );
    System.out.println( "After the loop" );
  4. Use a while loop to complete the following code based on the description in the comment header:
    /**
     * Continually prompts that user until they enter "yes" or "no" and then displays their response
     * @author Hyrum D. Carroll
     * @version 0.2 (June 25, 2020)
     */
    
    import java.util.Scanner;
    
    public class UserResponse{
        public static void main( String[] args ){
            Scanner input = new Scanner(System.in);
    	String prompt = "May I have another cookie? ";
    	String response = "";
    
        
    
    
            System.out.println( "You entered " + response );
        }
    }
    
  5. Rewrite the while loop in UserResponse to be a do-while loop.
  6. Use a for loop to complete the following code based on the description in the comment header:
    /**
     * Counts up by powers of powers of 2 (starting at 1 until UPPER_LIMIT, which is 1,000,000)
     * @author Hyrum D. Carroll
     * @version 0.3 (June 25, 2020)
     */
    public class PowersOfTwo{
    
        
    
        public static void main( String[] args ){
    
    	
    
        }
    }
    
  7. Replace the if statement with an equivalent switch statement:
    /**
    * Returns the log base 2 (for powers of 2)
    * @param number A power of 2
    * @return the log base 2 of number
    */
    public static int logBase2( int number ){
        int log;
        if( number == 1){
            log = 0;
        }else if( number == 2 ){
            log = 1;
        }else if( number == 4 ){
            log = 2;
        }else if( number == 8 ){
            log = 3;
        }else if( number == 16 ){
            log = 4;
        }else if( number == 32 ){
            log = 5;
        }else if( number == 64 ){
            log = 6;
        }else if( number == 128 ){
            log = 7;
        }else if( number == 256 ){
            log = 8;
        }else if( number == 512 ){
            log = 9;
        }else{
            log = -1;
        }
    
        return log;
    }