Java Controls

Sang Shin, sang.shin@sun.com, Sun Microsystems, www.javapassion.com/javaintro


In this lab, you are going to build and run sample applications that uses control structure of the Java programming language such as while loop or if/else.


Expected duration: 90 minutes


Software Needed

Before you begin, you need to install the following software on your computer.


Change Log



Lab Exercises


Exercise 1: if/else control structure

In this exercise,  you will learn how to write a Java program that uses if/else control structure.

(1.1) Build and run a Java program that uses if/else control structure

1.  Open MyGradesProject NetBeans project. 


Figure-1.10: Open MyGradesProject
2. Study the Grades.java which uses if/else control structure,
import javax.swing.JOptionPane;

public class Grades {
   
    public static void main(String[] args) {
       
        int mathGrade = 0;
        int historyGrade = 0;
        int scienceGrade = 0;
        double average = 0;
       
        mathGrade = Integer.parseInt(JOptionPane.showInputDialog("Enter math grade between 0 and 100!"));
        historyGrade = Integer.parseInt(JOptionPane.showInputDialog("Enter history grade between 0 and 100!"));
        scienceGrade = Integer.parseInt(JOptionPane.showInputDialog("Enter science grade between 0 and 100!"));
       
        // Compute average
        average = (mathGrade+historyGrade+scienceGrade)/3;
       
        // Perform if & else control
        if (average >= 60){
            JOptionPane.showMessageDialog(null, "Good job! Your average is " + average);
        } else{
            JOptionPane.showMessageDialog(null, "You need to do better! Your average is " + average);
        }
       
    }
}
Code-1.11: Grades.java

3. Build and run the program

Figure-1.12: Enter math grade dialog box


Figure-1.13: Enter history grade dialog box


Figure-1.14: Enter science grade dialog box


Figure-1.15: Computing average and display different message using if/else


4. (For your own exercise - this is not a homework) Modify the Grades.java as following:

                                                                                                                        return to top of the exercise


(1.2) Build and run another Java program that uses if/else control structure


1.  Open MyNumWordsProject NetBeans project. 

2. Study the NumWords.java which uses if/else control structure,
import javax.swing.JOptionPane;

public class NumWords {
   
    /** Creates a new instance of NumWords */
    public NumWords() {
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String msg = "";
        int input = 0;
       
        // Get the input string
        input = Integer.parseInt(JOptionPane.showInputDialog
                ("Enter number between 1 to 10"));
       
        // Set msg variable to the string equivalent of input
        if(input == 1)        msg = "one";
        else if(input == 2)    msg = "two";
        else if(input == 3)    msg = "three";
        else if(input == 4)    msg = "four";
        else if(input == 5)    msg = "five";
        else if(input == 6)    msg = "six";
        else if(input == 7)    msg = "seven";
        else if(input == 8)    msg = "eight";
        else if(input == 9)    msg = "nine";
        else if(input == 10)    msg = "ten";
        else            msg = "Invalid number";
       
        // Display the number in words if with in range
        JOptionPane.showMessageDialog(null,msg);
    }
}
Code-1.21: NumWords.java

3. Build and run the program

Figure-1.22: Enter a number


Figure-1.23: Display string equivalent of the number entered

                                                                                                                        return to top of the exercise


Summary

In this exercise, you learned how to if/else control structure of the Java programming language.
   
                                                                                                                                   Return to the top


Exercise 2: for loop

In this exercise, you will learn how to write a Java program that uses for loop.

  1. Build and run a Java program that uses for loop

(2.1) Build and run a Java program that uses a for loop

1.  Open MyForLoopProject NetBeans project. 


2. Study the ForLoop.java which uses if/else control structure,
import javax.swing.JOptionPane;

public class ForLoop {
   
    /** Creates a new instance of ForLoop */
    public ForLoop() {
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Declare and initialize String array variable called names.
        String names []={"Beah","Bianca","Lance","Belle","Nico","Yza","Gem","Ethan"};
       
        // This is the search string we are going to use to search the array.
        String searchName = JOptionPane.showInputDialog("Enter either \"Yza\" or \"noname\"!");
       
        // Declare and initialize boolean primitive type variable called foundName.
        boolean foundName =false;
       
        // Search the String array using for loop.
        //  * The "names.length" is the size of the array.
        //  * This for loop compares the value of each entry of the array with
        //     the value of searchString String type variable.
        //  * The equals(..) is a method of String class. Think about why you
        //     cannot use "names[i] == searchName" as comparison logic here.

        for (int i=0; i<names.length; i++){
            if (names [i ].equals(searchName)){
                foundName =true;
                break;
            }
        }
       
        // Display the result
        if (foundName)
            JOptionPane.showMessageDialog(null, searchName + " is found!");
        else
            JOptionPane.showMessageDialog(null, searchName + " is not found!");
       
    }
   
}
Code-2.21: ForLoop.java

3. Build and run the program

Figure-2.22: Enter search string


Figure-2.23: Yza is found

Figure-2.24: Enter search string


Figure-2.25: noname is not found


Summary

In this exercise, you learned how to use a for loop.

                                                                                                                        return to the top



Exercise 3: while loop

In this exercise, you will learn how to write Java programs that use while and do-while loop.

  1. Build and run a Java program that uses while loop
  2. Build and run a Java program that uses do-while loop

(3.1) Build and run a Java program that uses a while loop

1.  Open MyFiveNamesUsingwhileProject NetBeans project. 

2. Study the FiveNamesUsingwhile.java which uses if/else control structure,
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class FiveNamesUsingwhile {
   
    /**
     * Creates a new instance of FiveNamesUsingwhile
     */
    public FiveNamesUsingwhile() {
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        BufferedReader reader
                = new BufferedReader(new InputStreamReader(System.in));
        String name = "";
        int counter = 0;
       
        //gets the users' name
        try{
            System.out.println("Enter name: ");
            name = reader.readLine();
        }catch(Exception e){
            System.out.println("Invalid input");
            System.exit(0);
        }
       
        // while loop that prints the name five times
        while (counter < 5){
            System.out.println(name);
            counter++;
        }
    }
}
Code-3.11: FiveNamesUsingwhile.java

3. Build and run the program

Figure-3.12: Enter your name

Figure-3.13: Name is repeated 5 times using while loop

                                                                                                                        return to top of the exercise

(3.2) Build and run a Java program that uses a do-while loop

1.  Open MyFiveNamesUsingdowhileProject NetBeans project. 

2. Study the FiveNamesUsingdowhile.java which uses if/else control structure,
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class FiveNamesUsingdowhile {
   
    public static void main(String[] args){
       
        BufferedReader reader
                = new BufferedReader(new InputStreamReader(System.in));
        String name = "";
        int counter = 0;
       
        //gets the users' name
        try{
            System.out.println("Enter name: ");
            name = reader.readLine();
        }catch(Exception e){
            System.out.println("Invalid input");
            System.exit(0);
        }
       
        // Use do-while loop that prints the name five times
        do{
            System.out.println(name);
            counter++;
        }while(counter < 5);
    }
   
}
Code-3.21: FiveNamesUsingdowhile.java

3. Build and run the program
                                                                                                                        return to top of the exercise

Summary

In this exercise, you learned how to use while and do-while loop.

                                                                                                                                  return to the top


Homework exercise (for people who are taking Sang Shin's "Java Programming online course")


1. The homework is to modify the MyForLoopProject project (Exercise 2 above) described below.   (You might want to create a new project by copying the MyForLoopProject project.)  You can name the new project in any way you want but here I am going to call to call it as MyOwnWhileProject
2. Send the following files to javaprogramminghomework@sun.com with Subject as JavaIntro-javacontrol.