2 Introduction Ⅰ

Introduction Ⅰ

Objective

  • Use an IDE to develop and run applications.
  • Use input/output statements.
  • Use control statements.
  • Debug programs.

Exercise 1*

Experiment with a Java Program

  • Create a project and under the src folder create a file called Hello.java in which you define the following class:

    Hello.java
    public class Hello {
      public static void main(String[] args) {
        System.out.print("Hello and welcome to CMPS 251!");
      }
    }
  • Run the file that you just created. What was the output?

  • Perform the following experiments and record your findings:

    • Remove the first public keyword. Does the class compile? Does it run? Restore the public keyword.
    • Remove the second public keyword. Does the class compile? Does it run? Restore the public keyword.
    • Remove the static keyword. Does the class compile? Does it run? Restore the static keyword.
    • Remove the void keyword. Does the class compile? Does it run? Restore the void keyword.
    • Replace the void keyword with int and add a return 0; statement just before the end of the main method. Does the class compile? Does it run? Restore the void keyword.
    • Rewrite the method name as Main instead of main. Does the class compile? Does it run? Restore the main method name.
    • Change the type of the args array from String to int. Does the class compile? Does it run? Restore args’s data type.
    • Change the argument name from args to myArgs. Does the class compile? Does it run? Restore args’s name.
    • Change the argument from String[] args to String args[]. Does the class compile? Does it run?
  • What is the conclusion from the above experiments?

  • Change the program so that it outputs your name repeated 6 times, printed in one line, and separated with the tab character, using a while loop.

  • Repeat the above but use a do/while loop instead.

Solution
App1.java
public class App1 {
  public static void main(String[] args) {
    int index = 0;
    while (index < 6) {
      System.out.print("Dane Doe"
                       + "\t");
      index += 1;
    }
  }
}
App1.java
public class App2 {
  public static void main(String[] args) {
    int index = 0;
    do {
      System.out.print("Dane Doe"
                       + "\t");
      index += 1;
    } while (index < 6);
  }
}

Exercise 2*

What is output by the following program? Assume the user enters 65 for one execution of the program and 59 for a second execution.

Compare1.java
import java.util.Scanner;
 
public class Compare1 {
  public static void main(String[] args) {
    int mark;
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter mark (an integer): ");
    mark = scanner.nextInt();
    if ((mark / 20) >= 3) {
      System.out.println("Pass");
    } else {
      System.out.println("Fail");
    }
    scanner.close();
  }
}

switch Statement

  • Unlike an if statement (single selection) and if/else (double selection), switch is a multiple selection statement which allows a variable to be tested for equality against a list of values.
  • Each value is called a case, and the variable being switched on is checked for each case.
  • A switch works with the byte, short, char, and int primitive data types and with String.
  1. Make a copy of the Compare1 class and name it Compare2.

  2. Replace the if/else statement with a switch that displays the following messages based on the values of the switch selector:

    Value(s)Message
    4, 5Excellent
    3Very Good
    2Good
    All other valuesFail
Solution
Compare2.java
import java.util.Scanner;
 
public class Compare2 {
  public static void main(String[] args) {
    int mark;
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter mark (an integer): ");
    mark = scanner.nextInt();
 
    switch (mark) {
    case 5:
    case 4:
      System.out.println("Excellent");
      break;
    case 3:
      System.out.println("Very good");
      break;
    case 2:
      System.out.println("Good");
      break;
    default:
      System.out.println("Fail");
    }
 
    scanner.close();
  }
}

Exercise 3*

Introducing System.out.printf() and String.format()

The following application outputs temperatures in Fahrenheit and their equivalent in Celsius:

TemperatureConverter.java
public class TemperatureConverter {
  public static void main(String[] args) {
    System.out.println("Fahrenheit"
                      + "\t"
                      + "Celsius");
    for (int fahr = 0; fahr <= 100; fahr += 10) {
      double cels = 5.0 * (fahr - 32) / 9.0;
      System.out.println(fahr + "\t" + cels);
    }
  }
}

Create a new project and a new class called TemperatureConverter with the above code then run it. The output should be similar to the following (partly shown here):

Fahrenheit Celsius
0       -17.77777777777778
10      -12.222222222222221
20      -6.666666666666667
...     ...
90      32.22222222222222
100     37.77777777777778
  1. What is the purpose of the "\t" which is used in the above code?

  2. Is it possible to use System.out.print() or System.out.println() to force the output of the Celsius values to be shown to two decimal places?

  3. The word Fahrenheit has 10 letters. Is it possible to output the values of Fahrenheit temperatures to be right-justified in a field width of 10 characters, similar to the following?

    Fahrenheit
             0
            10
           ...
           100

Using System.out.printf()

The System.out.printf() method provides us with the ability to do the above, and much more. Unlike System.out.print() and System.out.println(), the printf() method takes a formatting string that has “place holders” used to control the output format for our variables/expressions which must be passed as parameters to printf(), that is to say, they should be separated with a comma. For example:

  • "%d" is used to format numbers of type int, long, or byte. If you want to specify a field width of say 10 digits, then use "%10d" in the format string. The numbers will be output right-justified within this field.
  • "%f" is used to format numbers of type float or double. If you want to specify a field width of say 15 digits and 3 decimal places, then use "%15.3f" in the format string. The numbers will be output right-justified within this field.
  • "%s" is used for String formatting.

Please refer to your textbook for further details, when needed.

Now, modify the TemperatureConverter class so that its output is similar to the following:

Fahrenheit   Celsius
         0    -17.78
        10    -12.22
        20     -6.67
       ...       ...
        90     32.22
       100     37.78
Solution
TemperatureConverter.java
public class TemperatureConverter {
  public static void main(String[] args) {
    System.out.println("Fahrenheit"
                       + "\t"
                       + "Celsius");
    for (int fahr = 0; fahr <= 100; fahr += 10) {
      double cels = 5.0 * (fahr - 32) / 9.0;
      System.out.printf("%10d\t%7.2f%n", fahr, cels);
    }
  }
}

Using String.format()

The String.format() method allows you to format the output and store it in a string variable. This variable can then be output using the usual print() method. This method has the same signature as the printf() method and works in a similar fashion, except that the output is stored in a String variable rather than printed.

The advantage of this alternative becomes important when some graphical user interface (GUI) messages need to be formatted before placing them on the GUI component, as will be seen later. You can also store the formatted output in a String variable and then use the print() method to display it on the console in a single operation, as in the following:

  1. Now, make a copy of your TemperatureConverter class: Copy the file and rename it to TemperatureConverter2.java.

  2. Add a String variable inside the for loop just after the line that defines and calculates the cels variable:

    String formattedLine = String.format(/*insert the same args of the printf() method*/);
  3. Replace printf(...) with print(formattedLine), then save and run. You should get the same output as before.

Solution
TemperatureConverter2.java
public class TemperatureConverter2 {
  public static void main(String[] args) {
    System.out.println("Fahrenheit"
                       + "\t"
                       + "Celsius");
    for (int fahr = 0; fahr <= 100; fahr += 10) {
      double cels = 5.0 * (fahr - 32) / 9.0;
      String result = String.format("%10d\t%7.2f%n", fahr, cels);
      System.out.print(result);
    }
  }
}

Exercise 4*

  • Debugging allows you to run a program interactively while watching the source code and the variables during the execution.

  • By breakpoints in the source code you specify where the execution of the program should stop.

  • Once the program is stopped you can investigate variables and change their content.

  • Your IDE has a special mode for debugging, which gives you a pre-configured set of views. In this mode, you control the execution process of your program and can investigate the state of the variables.

  • Let’s debug the following program and monitor how the for loop is executed.

    Experiment1.java
    public class Experiment1 {
      public static void main(String[] args) {
        int counter = 10;
        for (int i = 0; i <= 4; i++) {
          counter = counter + i;
        }
        System.out.println("Counter = " + counter);
      }
    }
  • To start debugging, add a breakpoint at the statement which you want to start from by right clicking on the left bar and selecting Add Breakpoint or clicking on the red disk next to the corresponding line number. You can also use Toggle Breakpoint or press F9 at the current line.

  • Start debugging by clicking on the menu RunStart Debugging or pressing F5. You can also click on the Debug Java button .

  • As you Step Over you will see how the program is executed and monitor the values of the variables in scope.

  • You can also Step Into a block or Step Out of it.

  • The last statement is printed when it is reached at the end of the program.

Exercise 5

switch Statement

  1. Write an application that prints the month of the year depending on the value of an integer variable month.

    Enter month: 9
    September
Solution
MonthName.java
import java.util.Scanner;
 
public class MonthName {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("Enter month: ");
    int month = scanner.nextInt();
 
    switch (month) {
    case 1:
      System.out.println("January");
      break;
    case 2:
      System.out.println("February");
      break;
    case 3:
      System.out.println("March");
      break;
    case 4:
      System.out.println("April");
      break;
    case 5:
      System.out.println("May");
      break;
    case 6:
      System.out.println("June");
      break;
    case 7:
      System.out.println("July");
      break;
    case 8:
      System.out.println("August");
      break;
    case 9:
      System.out.println("September");
      break;
    case 10:
      System.out.println("October");
      break;
    case 11:
      System.out.println("November");
      break;
    case 12:
      System.out.println("December");
      break;
    default:
      System.out.println("Invalid input");
    }
 
    scanner.close();
  }
}
  1. Modify the previous application such that it reads the name of the month and prints its number. Hint: use a String variable.

    Enter month: May
    5
Solution
NameMonth.java
import java.util.Scanner;
 
public class NameMonth {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("Enter month: ");
    String month = scanner.next();
 
    switch (month) {
    case "January":
      System.out.println(1);
      break;
    case "February":
      System.out.println(2);
      break;
    case "March":
      System.out.println(3);
      break;
    case "April":
      System.out.println(4);
      break;
    case "May":
      System.out.println(5);
      break;
    case "June":
      System.out.println(6);
      break;
    case "July":
      System.out.println(7);
      break;
    case "August":
      System.out.println(8);
      break;
    case "September":
      System.out.println(9);
      break;
    case "October":
      System.out.println(10);
      break;
    case "November":
      System.out.println(11);
      break;
    case "December":
      System.out.println(12);
      break;
    default:
      System.out.println("Invalid input");
    }
 
    scanner.close();
  }
}

Exercise 6

Arithmetic Operations

Write an application that performs the following:

  1. Read the marks of a student in three subjects: Math, Tech, and Music. Assume all marks are integer numbers. Use Scanner.nextInt() to read the marks.

  2. Calculate the total mark and the average mark.

  3. Determine the highest and the lowest of the three marks.

  4. Display the total mark, the average mark, the lowest mark, and the highest mark as shown in the sample output below.

    Enter Math's mark: 90
    Enter Tech's mark: 95
    Enter Music's mark: 85
     
    Highest mark is 95
    Lowest mark is 85
    Total mark is 270
    Average mark is 90
Solution
Marks.java
import java.util.Scanner;
 
public class Marks {
 
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("Enter Math's mark: ");
    int math = scanner.nextInt();
 
    System.out.print("Enter Tech's mark: ");
    int tech = scanner.nextInt();
 
    System.out.print("Enter Music's mark: ");
    int music = scanner.nextInt();
 
    int total, average, lowest, highest;
 
    total = math + tech + music;
    average = total / 3;
 
    highest = math;
    if (tech > highest) {
      highest = tech;
    }
    if (music > highest) {
      highest = music;
    }
 
    lowest = math;
    if (tech < lowest) {
      lowest = tech;
    }
    if (music < lowest) {
      lowest = music;
    }
 
    if (math >= tech && math >= music) {
      highest = math;
    } else if (tech >= math && tech >= music) {
      highest = tech;
    } else {
      highest = music;
    }
 
    if (math <= tech && math <= music) {
      lowest = math;
    } else if (tech <= math && tech <= music) {
      lowest = tech;
    } else {
      lowest = music;
    }
 
    System.out.println();
    System.out.println("Highest mark is " + highest);
    System.out.println("Lowest mark is " + lowest);
    System.out.println("Total mark is " + total);
    System.out.println("Average mark is " + average);
 
    scanner.close();
  }
}

Exercise 7

Write an application that outputs distance values measured in inches and their equivalent in centimeters for all distance values between 0 and 50 inches, inclusive, in steps of 2 inches.

The equation to convert inches to centimeters is: centimeters=2.54inches\text{centimeters} = 2.54 * \text{inches}. Format your inches values as integers and the centimeters values as real values displaying 2 decimal places after the decimal point.

0in = 0.00cm
2in = 5.08cm
4in = 10.16cm
6in = 15.24cm
8in = 20.32cm
10in = 25.40cm
12in = 30.48cm
14in = 35.56cm
16in = 40.64cm
18in = 45.72cm
20in = 50.80cm
22in = 55.88cm
24in = 60.96cm
26in = 66.04cm
28in = 71.12cm
30in = 76.20cm
32in = 81.28cm
34in = 86.36cm
36in = 91.44cm
38in = 96.52cm
40in = 101.60cm
42in = 106.68cm
44in = 111.76cm
46in = 116.84cm
48in = 121.92cm
50in = 127.00cm
Solution
InchCm.java
public class InchCm {
  public static void main(String[] args) {
    for (int inch = 0; inch <= 50; inch += 2) {
      double cm = 2.54 * inch;
      System.out.printf("%2din = %.2fcm%n", inch, cm);
    }
  }
}

Exercise 8+

Write an application to read the wattage (or Watts) of a standard light bulb and assign to a variable called lumens the expected brightness of that bulb. Use this table:

WattsBrightness
15125
25215
40500
60880
751000
1001675

Use a switch statement and assign a value of -1 if the value of Watts is not in the table.

Bulb wattage: 40
Bulb brightness: 500lm
Bulb wattage: 1
Undefined brightness.
Solution
Wattage.java
import java.util.Scanner;
 
public class Wattage {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("Bulb wattage: ");
    int watts = scanner.nextInt();
    int lumens;
 
    switch (watts) {
    case 15:
      lumens = 125;
      break;
    case 25:
      lumens = 215;
      break;
    case 40:
      lumens = 500;
      break;
    case 60:
      lumens = 880;
      break;
    case 75:
      lumens = 1000;
      break;
    case 100:
      lumens = 1675;
      break;
    default:
      lumens = -1;
      break;
    }
 
    if (lumens != -1) {
      System.out.printf("Bulb brightness: %dlm%n", lumens);
    } else {
      System.out.println("Undefined brightness.");
    }
 
    scanner.close();
  }
}

Exercise 9+

  1. Write an application to evaluate the following equation, where nn is an odd number entered by the user:

    y=12+34+56++nn+1\begin{align*} y &= \frac{1}{2} + \frac{3}{4} + \frac{5}{6} + \cdots + \frac{n}{n+1} \end{align*}
    Enter an odd positive integer: 4
    Invalid input.
    Enter an odd positive integer: 11
    Result: 4.775
Solution
Sum1.java
import java.util.Scanner;
 
public class Sum1 {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("Enter an odd positive integer: ");
    int n = scanner.nextInt();
 
    if (n % 2 == 0) {
      System.out.println("Invalid input.");
    } else {
      double s = 0;
      for (int i = 1; i <= n; i += 2) {
        s += (double)i / (i + 1);
      }
 
      System.out.printf("Result: %.3f%n", s);
    }
 
    scanner.close();
  }
}
  1. Extend you application to evaluate the following equation:

    y=12!+34!+56!++n(n+1)!\begin{align*} y &= \frac{1}{2!} + \frac{3}{4!} + \frac{5}{6!} + \cdots + \frac{n}{(n+1)!} \end{align*}
    Enter an odd positive integer: 11
    Result: 0.6321205586787184
Solution
Sum2.java
import java.util.Scanner;
 
public class Sum2 {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
 
    System.out.print("Enter an odd positive integer: ");
    int n = scanner.nextInt();
 
    if (n % 2 == 0) {
      System.out.println("Invalid input.");
    } else {
      double s = 0;
      int fact = 1;
      for (int i = 1; i <= n; i += 2) {
        fact *= i * (i + 1);
        s += (double)i / fact;
      }
 
      System.out.printf("Result: %.16f%n", s);
    }
 
    scanner.close();
  }
}