sample solutions

advertisement
Laboratory 5
Lesson 5-2
Exercise 1
Exercise 2
Exercise 3
Lesson 5-3
Exercise 1
Exercise 2
Lesson 5-4
Exercise 1
Exercise 2
Exercise 3
Exercise 4
Lesson 5-5
Exercise 1
Exercise 2
Exercise 3
Exercise 4
Lesson 5-6
Exercise 1
Exercise 2
Exercise 3
Solutions
Lesson 5-2
Exercise 1:
The if statement is
if ( grade >= 80 )
System.out.println( "Congratulations!" );
Use the following input grade values: 60, 100, 80, 81, and 79.
“Congratulations!” is printed three times in the five runs.
Exercise 2:
if ( grade < 70 )
System.out.println( "Try harder" );
Use the following input grade values: 60, 100, 80, 81, and 79.
“Try harder” is printed once in the five runs.
Exercise 3:
if ( grade >= 70 && grade < 80 )
System.out.println( "Average" );
Use the following input grade values: 60, 100, 80, 81, and 79.
“Average” is printed once in the five runs.
The complete program that demonstrates all three exercises may resemble the following.
// Application Grade prints appropriate messages on
// System.out based on a grade read from the keyboard
import java.util.Scanner;
public class Grade
{
public static void main(String[] args)
{
int grade;
Scanner inData = new Scanner(System.in);
System.out.println("Key in an integer grade. ");
grade = inData.nextInt();
//Exercise 1
if ( grade >= 80 )
System.out.println( "Congratulations!" );
//Exercise 2
if ( grade < 70 )
System.out.println( "Try harder" );
//Exercise 3
if ( grade >= 70 && grade < 80 )
System.out.println( "Average" );
}
}
The following are the five runs.
Run1:
Key in an integer grade.
60
Try harder
Run2:
Key in an integer grade.
100
Congratulations!
Run3:
Key in an integer grade.
80
Congratulations!
Run4:
Key in an integer grade.
81
Congratulations!
Run5:
Key in an integer grade.
79
Average
Lesson 5-3
Exercise 1:
The following statement reads in the pressure reading, and writes a warning message if
the pressure is greater than 100.
System.out.println("Key in an integer pressure. ");
pressure = inData.nextInt();
if (pressure > 100)
System.out.println("Warning!! Pressure reading above danger limit.");
Use the following input pressure values: 6, 76, 80, 99, 0, 100, 110, and 199.
The warning message is printed twice in the eight runs.
Exercise 2:
The following statement writes a normal message if the pressure reading is lower than
100 but greater than 6.
if ((pressure < 100) && (pressure > 6))
System.out.println("Everything seems normal.");
Use the following input pressure values: 6, 76, 80, 99, 0, 100, 110, and 199
The normal message is printed three times in the eight runs.
An example of a program that incorporates both exercises follows. This code also
demonstrates a potential logic error when using a series of separate ‘if’ statements, rather
than a single ‘if-else’ statement. The program ignores a pressure of exactly 100.
import java.util.Scanner;
public class Pressure
{
public static void main(String[] args)
{
int pressure;
Scanner inData = new Scanner(System.in);
//Exercise 1
System.out.println("Key in an integer pressure. ");
pressure = inData.nextInt();
if (pressure > 100)
System.out.println
("Warning!! Pressure reading above danger limit.");
// Exercise 2
if ((pressure < 100) && (pressure > 6))
System.out.println("Everything seems normal.");
}
}
The following are the eight runs.
Run1:
Key in an integer pressure.
6
Run 2:
Key in an integer pressure.
76
Everything seems normal.
Run 3:
Key in an integer pressure.
80
Everything seems normal.
Run 4:
Key in an integer pressure.
99
Everything seems normal.
Run 5:
Key in an integer pressure.
0
Run 6:
Key in an integer pressure.
100
Run 7:
Key in an integer pressure.
110
Warning!! Pressure reading above danger limit.
Run 8:
Key in an integer pressure.
199
Warning!! Pressure reading above danger limit.
Lesson 5-4
Exercise 1:
See Lesson 5-3. The complete program is provided in Exercise 2.
The warning message is printed twice in the eight runs.
The normal message is printed three times in the eight runs.
Exercise 2:
The required statements are
// Input name of food item.
System.out.println("Enter name of food item.");
foodItem = inData.nextLine();
// Input number of calories
System.out.println("Enter number of calories.");
calories = inData.nextInt();
// Input grams of fat
System.out.println("Enter grams of fat.");
gramsOfFat = inData.nextInt();
// Calculate percentage fat from calories and print result
fatCalPercent = (double)(gramsOfFat*9)/calories*100.0;
System.out.println(foodItem + " percentage of calories from fat is: " +
fatCalPercent);
The results are shown in the ‘Percent from Fat’ column.
Item
Grams of Fat
Calories
Percent from Fat
Tuna
Spaetzle
V8 Juice
Corned Beef
1
2
0
8
60
170
36
200
15
10.588
0
36
Exercise 3:
The following statement prints one of two possible messages, depending on the
percentage of calories from fat.
if (fatCalPercent > 30.0)
System.out.println("This item is NOT Heart Healthy!");
else
System.out.println("This item is Heart Healthy!");
Tuna, Spaetzle, and V8 juice are heart healthy.
Corned beef is NOT heart healthy.
Exercise 4:
An alternative to the four listed foods has been used.
A sample program for Exercise 2, 3, and 4 is
// Application PerCent calculates a person's percentage of
// calories from fat and prints an appropriate message
import java.util.Scanner;
public class PerCent
{
public static void main(String[] args)
{
Scanner inData = new Scanner(System.in);
String foodItem;
int gramsOfFat;
int calories;
double fatCalPercent;
// Exercise 2
// Input name of food item.
System.out.println("Enter name of food item.");
foodItem = inData.nextLine();
// Input number of calories
System.out.println("Enter number of calories.");
calories = inData.nextInt();
// Input grams of fat
System.out.println("Enter grams of fat.");
gramsOfFat = inData.nextInt();
// Calculate percentage fat from calories and print result
fatCalPercent = (double)(gramsOfFat*9)/calories*100.0;
System.out.println(foodItem+" percentage of calories from fat is: "
+ fatCalPercent);
// Exercise 3
if (fatCalPercent > 30.0)
System.out.println("This item is NOT Heart Healthy!");
else
System.out.println("This item is Heart Healthy!");
}
}
The following are the four runs.
Run1:
Enter name of food item.
Tuna
Enter number of calories.
60
Enter grams of fat.
1
Tuna percentage of calories from fat is: 15.0
This item is Heart Healthy!
Run2:
Enter name of food item.
Spaetzle
Enter number of calories.
170
Enter grams of fat.
2
Spaetzle percentage of calories from fat is: 10.588235294117647
This item is Heart Healthy!
Run3:
Enter name of food item.
V8 Juice
Enter number of calories.
36
Enter grams of fat.
0
V8 Juice percentage of calories from fat is: 0.0
This item is Heart Healthy!
Run4:
Enter name of food item.
Corned Beef
Enter number of calories.
200
Enter grams of fat.
8
Corned Beef percentage of calories from fat is: 36.0
This item is NOT Heart Healthy!
Lesson 5-5
Exercise 1:
A sample solution for Exercise 1 is
// Application Temp inputs a temperature and prints an
// appropriate message
import java.util.Scanner;
public class Temp
{
public static void main(String[] args)
{
int temperature;
Scanner inData = new Scanner(System.in);
System.out.println("Enter temperature.");
temperature = inData.nextInt();
// exercise 1
if (temperature > 90)
System.out.println("Visit a neighbor");
if ((temperature > 80) && (temperature <= 90))
System.out.println("Turn on air conditioning");
if ((temperature > 70) && (temperature <= 80))
System.out.println("Do nothing");
if ((temperature > 66) && (temperature <= 70))
System.out.println("Turn on heat");
if (temperature <= 66)
System.out.println("Visit a neighbor");
}
}
You need at least five runs to ensure that each ‘if’ statement is tested.
A sample set of data could be 91, 81, 71, 68, and 60.
Exercise 2:
A sample solution for Exercise 2 is
// Application Temp inputs a temperature and prints an
// appropriate message
import java.util.Scanner;
public class Temp
{
public static void main(String[] args)
{
int temperature;
Scanner inData = new Scanner(System.in);
System.out.println("Enter temperature.");
temperature = inData.nextInt();
// exercise 2
if (temperature > 90)
System.out.println("Visit a neighbor");
else if ((temperature > 80) && (temperature <= 90))
System.out.println("Turn on air conditioning");
else if ((temperature > 70) && (temperature <= 80))
System.out.println("Do nothing");
else if ((temperature > 66) && (temperature <= 70))
System.out.println("Turn on heat");
else
System.out.println("Visit a neighbor");
}
}
Using the sample set of data used in Exercise 1 (91, 81, 71, 68, and 60), the solution for
Exercise 2 gives the same results.
Note: The ‘if-else’ solution is the safer solution, as it covers all possible conditions. See
the comment in Lesson 5-3: Exercise 2.
Exercise 3:
A sample solution for Exercise 3 is
// Application HiScore reads and prints three test scores.
// The largest value of the three is printed with an
// appropriate message
// Assumption: The scores are unique
import java.util.Scanner;
public class HiScore
{
public static int largest( int one,int two, int three )
{
int largest = two;
if ( one > largest )
largest = one;
if ( three > largest )
largest = three;
return largest;
}
public static void main(String[] args)
{
Scanner inData = new Scanner(System.in);
int score1;
int score2;
int score3;
// Prompt for and read in scores
System.out.println("Enter three test scores.");
score1 = inData.nextInt();
score2 = inData.nextInt();
score3 = inData.nextInt();
System.out.println();
System.out.println( "The test scores are " + score1 + ", "
+ score2 + ", and " + score3 + ".");
System.out.println( "The highest is " +
largest( score1, score2, score3 ) + "." );
}
}
For the following six sets of input values,
100
100
70
80
80
70
80
70
80
70
100
100
70
80
100
100
70
80
the program always gives the same result (the highest score). For example,
Enter three test scores.
80
70
100
The test scores are 80, 70, and 100.
The highest is 100.
Exercise 4:
Yes.
The above six sets of input values (see Exercise 3) represent six different ways to enter
the scores 70, 80, and 100. They cover all possible variations of high to low for three
numbers (scores).
To test the application (the method ‘largest’) for any three input scores, we need to enter
the scores in all possible input combinations. Any three scores can be entered in six
different ways, as follows:
Run 1:
Run 2:
Run 3:
Run 4:
Run 5:
Run 6:
score1 score 2 score 3
score1 score 3 score 2
score2 score 3 score 1
score3 score 2 score 1
score2 score 1 score 3
score3 score 1 score 2
Lesson 5-6
Exercise 1:
The syntax errors are:
- Error 1: line 17
The comesFirst method returns a String, but its return type is an int.
In the method declaration, ‘int’ should be replaced with ‘String’.
- Error 2: line 33
The comesFirst is an instance method. Line 33 calls it a class (static) method.
To correct the problem, declare the comesFirst as a class (static) method.
The corrected application is
// Application ComesFirst reads and prints three words.
// The word that comes first in the alphabet is printed with an
// appropriate message
// Assumption: The words are unique
import java.util.Scanner;
public class ComesFirst
{
public static String comesFirst(String one, String two, String three)
{
String first = " ";
if (one.compareTo(two) > 0)
first = one;
else
first = two;
if (three.compareTo(first) > 0)
first = three;
return first;
}
public static void main(String[] args)
{
Scanner inData = new Scanner(System.in);
String word1;
String word2;
String word3;
// Prompt for and read in words
System.out.println("Enter three words.");
word1 = inData.nextLine();
word2 = inData.nextLine();
word3 = inData.nextLine();
System.out.println("The test words are " + word1 + ", " +
word2 + ", " + word3);
System.out.println(comesFirst(word1, word2, word3)
+ " comes first");
}
}
Exercise 2:
The following is the initial program output.
Enter three words.
alpha
beta
gamma
The test words are alpha, beta, gamma
gamma comes first
The answer is incorrect.
The comesFirst method should return the word that comes first in the alphabet. Instead, it
returns the word that comes last in the alphabet.
The Boolean expressions need to be corrected. Both expressions should use the “less
than”, (<) not the “greater than” (>), operator.
The revised program is
// Application ComesFirst reads and prints three words.
// The word that comes first in the alphabet is printed with an
// appropriate message
// Assumption: The words are unique
import java.util.Scanner;
public class ComesFirst
{
public static String comesFirst(String one, String two, String three)
{
String first = " ";
if (one.compareTo(two) < 0 )
first = one;
else
first = two;
if (three.compareTo(first) < 0 )
first = three;
return first;
}
public static void main(String[] args)
{
Scanner inData = new Scanner(System.in);
String word1;
String word2;
String word3;
// Prompt for and read in words
System.out.println("Enter three words.");
word1 = inData.nextLine();
word2 = inData.nextLine();
word3 = inData.nextLine();
System.out.println("The test words are " + word1 + ", " +
word2 + ", " + word3);
System.out.println(comesFirst(word1, word2, word3)
+ " comes first");
}
}
The program output will now be correct.
Enter three words.
alpha
beta
gamma
The test words are alpha, beta, gamma
alpha comes first
Exercise 3:
The program expects three lines of input. If we enter the following data
alpha beta gamma
on a single line, we still need to press ‘Enter’ for the second and third line. If this is done,
the program will compare the above input line with the two empty strings (the second and
third lines). The following is the program run (comments added on the right):
Enter three words.
alpha beta gamma
//first input line
//second input line (empty string)
//third input line (empty string)
The test words are alpha beta gamma, ,
comes first
The revised application (below) allows the data to be read either way. The application
should read in individual tokens (which could be on single or multiple lines), rather than
complete lines. “inData.nextLine()” statements are replaced with “inData.next()”.
// Application ComesFirst reads and prints three words.
// The word that comes first in the alphabet is printed with an
// appropriate message
// Assumption: The words are unique
import java.util.Scanner;
public class ComesFirst
{
public static String comesFirst(String one, String two, String three)
{
String first = " ";
if (one.compareTo(two) < 0 ) //> 0)
first = one;
else
first = two;
if (three.compareTo(first) < 0 ) //> 0)
first = three;
return first;
}
public static void main(String[] args)
{
Scanner inData = new Scanner(System.in);
String word1;
String word2;
String word3;
// Prompt for and read in words
System.out.println("Enter three words.");
word1 = inData.next();
word2 = inData.next();
word3 = inData.next();
System.out.println("The test words are " + word1 + ", " +
word2 + ", " + word3);
System.out.println(comesFirst(word1, word2, word3)
+ " comes first");
}
}
The following are two runs that demonstrate both input methods.
Enter three words.
alpha beta gamma
The test words are alpha, beta, gamma
alpha comes first
Enter three words.
alpha
beta
gamma
The test words are alpha, beta, gamma
alpha comes first
Download