Welcome to Lesson 7!
|
Alphabetical Order |
Example | Result |
First String comes BEFORE second String |
"cat".compareTo("dog"); | Negative Number |
Two Strings are EQUAL |
"cat".compareTo("cat"); |
0 |
First String comes AFTER second String |
"dog".compareTo("cat"); |
Positive Number |
- According to Oracle's String API, the numerical value generated by compareTo is the difference in unicode values between the first differing characters in the two Strings.
Example Program Comparing Strings
|
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String s1, s2;
|
Activity 7.1: Let's Alphabetize! (10 pts)
- Open up Eclipse and create a new Java project called Activity7, with a new class called Alphabetize.java
- Our program will take in two String inputs from the user, compare then and the output the two Strings in alphabetical order.
- At the top of your program, declare a String variables called word1.
- Now declare a second String variable called word2.
- Next, write a System.out.println statement welcoming your user to the program and letting them know that this program will alphabetize two words.
- Run your program to make sure it is giving you the output you expected.
- Let's prompt the user for the first word and store the result as word1.
word1 = input.next(); //assumes new Scanner declared at top of program
- Do the same for the second word.
- Now, let's create an if-else statement to determine the ordering of the two words. And, then output the result to our user. The if-else statement will need to use String comparison as discussed above.
- The code that you have written could be a useful part of a larger program.
- Submit your program to Canvas when finished.
3. Making Decisions Continued
"Nesting" if Statements
- The inner
if
statement is evaluated only if the test condition of the outerif
test first evaluates totrue
- The following code shows an example of a nested if statement
Example Showing a Nested if
Statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public static void main(String[] args) { |
Nesting in the else
Clause
- You can also nest
if
statements in theelse
clause - When used this way, the computer can make only one selection
- As soon as a condition is found to be true, the rest of the selections are ignored
- The following code shows an example of a nested
else if
statement - For example:
if (guess < 7) { System.out.println("Your guess is too low."); } else if (guess > 7) { System.out.println("Your guess is too high."); } else { System.out.println("*** Correct! ***"); }
- The trick in understanding this type of logic is to remember:
- You start at the top
- The computer makes only one selection
- Once the selection is made and processes, the computer skips the rest of the options
Example Showing a Nested if else
Statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public static void main(String[] args) {
|
Programming Style: Indentation of if-else-if Statements
- Note the alignment of the nested statements below:
- Each statement inside of the if, else if or else clauses need to be indented.
if (guess < 7) { System.out.println("Your guess is too low."); } else if (guess > 7) { System.out.println("Your guess is too high."); } else { System.out.println("*** Correct! ***"); }
- This shows more clearly that we are making a single choice among multiple alternatives
- Also, it prevents indentations from cascading to the right as we add more selections
Multiple Alternatives
- By using collections of if-else statements, a program can distinguish between multiple alternatives
Choosing Between Alternatives
- This program has five alternatives to choose from:
- "penny"
- "nickel"
- "dime"
- "quarter"
- erroneous input
- Note that the order that the alternatives are checked is unimportant
- We can follow the alternatives in the flowchart shown below
Flowchart of Multiple Alternative for Converting Coins to Values
- For example, consider the following example where a user enters the name of a coin, and the program displays the value:
Program Converting Coin Names to Values
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter coin name: "); String name = input.next();
double value = 0; if (name.equals("penny")) { value = 0.01; } else if (name.equals("nickel")) { value = 0.05; } else if (name.equals("dime")) { value = 0.10; } else if (name.equals("quarter")) { value = 0.25; } else { System.out.println(name + " is not a valid coin name"); }
System.out.println("Value = " + value); }
Importance of Using if-else-if
Structure
- Note that we cannot remove the
else
portion of the structure like shown below:
Scanner input = new Scanner(System.in);
System.out.print("Enter a magnitude on the Richter scale: ");
double richter = input.nextDouble();
if (richter >= 8.0) { // Does not use else
System.out.println("Most structures fall");
}
if (richter >= 7.0) {
System.out.println("Many buildings destroyed");
}
if (richter >= 6.0) {
System.out.println("Many buildings considerably damaged, some collapse");
}
if (richter >= 4.5) {
System.out.println("Damage to poorly constructed buildings");
}
if (richter >= 3.5) {
System.out.println("Felt by many people, no destruction");
}
if (richter >= 0) {
System.out.println("Generally not felt by people");
}
if (richter < 0) {
System.out.println("Negative numbers are not valid");
}
- The conditions must be exclusive and we need the else-if conditions to ensure exclusivity
- Independent
if
statements may cause a single input to print several messages
When Order Matters
- In some cases, the order of the tests is important
- For example, look at the following program from displays a description of the likely impact of an earthquake based on its magnitude on the Richter scale
Program Showing Multiple Alternatives Where Order Matters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public static void main(String[] args) {
|
Order Is Important
- Note that the order of the tests is important to ensure that the right results are printed
- If we rearranged the order of the
if-else
statements, we would get the wrong results - For example, if we reversed the order of the tests:
if (richter >= 0) { // tests in wrong order System.out.println("Generally not felt by people"); } else if (richter >= 3.5) { System.out.println("Felt by many people, no destruction"); } else if (richter >= 4.5) { System.out.println("Damage to poorly constructed buildings"); } else if (richter >= 6.0) { System.out.println("Many buildings considerably damaged, some collapse"); } else if (richter >= 7.0) { System.out.println("Many buildings destroyed"); } else if (richter >= 8.0) { System.out.println("Most structures fall"); } else { System.out.println("Negative numbers are not valid"); }
- This does not work because all values meet the first condition
- Every other test will never be attempted
Activity 7.2: Grades (10 pts)
- We want to write a program to calculate a student's letter grade according to the following table:
Numerical Grade Letter Grade greater than or equal to 90 A less than 90 but greater than or equal to 80 B less than 80 but greater than or equal to 70 C less than 70 but greater than or equal to 60 D less than 60 F
- Create a new class Grader.java inside of your Activity7 project folder.
- Add code to get user input into a variable named
score
of typedouble
. When you run the program after adding this code, the output should look like:Enter a score: 95.7
Make sure you declare the variable with a compatible data type. Note that the underlined numbers above shows what the user enters and is not part of your code.
- First we will look at a series of
if
statements and see thatif
statements alone are not enough to solve this problem. Copy the following into your program after the input statements:
{
}
{
}
{
}
{
}
{
}
- Here is problem occures.
- Write a multiline comment above main in which you describe the problem you see and why you think it is happening.
- To resolve this problem, convert your second - fourth if statements into else if statements, as shown below.
{
{
{
}
- Using else if makes each test condition of the
if
statement exclusive of the others - you tell the computer to find the first correct test condition, and then ignore all the rest of the test conditions.
- Compile
and run your modified program to make sure you made the changes
correctly. When you run the program, the output should look like:
Enter a score: 95 A
Run your program a few times with different score to verify that any score displays the correct letter grade.
- When finished, upload Grader.java to Canvas.
- What will the following output to the console?