Download Lab-Ch

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
4
Let’s all move one place on.
Control
Statements: Part 1
—Lewis Carroll
The wheel is come full circle.
—William Shakespeare
How many apples fell on
Newton’s head before he took
the hint!
—Robert Frost
OBJECTIVES
In this chapter you will learn:
■
All the evolution we know of
proceeds from the vague to
the definite.
—Charles Sanders Peirce
■
■
■
■
■
To use basic problem-solving techniques.
To develop algorithms through the process of top-down, stepwise
refinement.
To use the if and if…else selection statements to choose
among alternative actions.
To use the while repetition statement to execute statements in a
program repeatedly.
To use counter-controlled repetition and sentinel-controlled
repetition.
To use the assignment, increment and decrement operators.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Assignment Checklist
Name:
Date:
Section:
Exercises
Assigned: Circle assignments
Prelab Activities
Matching
YES
NO
Fill in the Blank
YES
NO
Short Answer
YES
NO
Programming Output
YES
NO
Correct the Code
YES
NO
YES
NO
Lab Exercises
Exercise 1 — Credit
Follow-Up Questions and Activities
Exercise 2 — Palindromes
Follow-Up Question and Activity
Exercise 3 — Largest Number
Follow-Up Question and Activity
Debugging
1, 2
YES
NO
1
YES
NO
1
YES
NO
Postlab Activities
Coding Exercises
1, 2, 3, 4, 5, 6
Programming Challenges
1, 2
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Date Due
99
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
101
Prelab Activities
Matching
Name:
Date:
Section:
After reading Chapter 4 of Java How to Program: Seventh Edition, answer the given questions. These questions
are intended to test and reinforce your understanding of key Java concepts. You may answer these questions either before or during the lab.
For each term in the left column, write the letter for the description that best matches the term from the right
column.
Term
Description
M
1.
--
a) Java’s only ternary operator.
I
2.
++
A
3.
?:
b) A selection statement that executes an indicated action
only when the condition is true.
K
4.
algorithm
H
5.
selection statement
O
6. sentinel-controlled repetition
P
7.
C
8. pseudocode
E
9. repetition statement
Q
10. counter-controlled repetition
G
11. program control
D
12. top-down, stepwise refinement
B
13.
if
F
14.
if…else
J
15. block
L
16.
N
17. primitive types
;
+=, -=, *=, /=, %=
c) An artificial and informal language that helps programmers develop algorithms.
d) A process for refining pseudocode by maintaining a
complete program representation for each refinement.
e) Allows the programmer to specify that an action is to be
repeated while some condition remains true.
f)
A selection statement that specifies separate actions to
execute when a condition is true and when a condition
is false.
g) Specifying the order in which statements are to be executed in a computer program.
h) Chooses among alternative courses of action in a program.
i)
Increment operator.
j)
A set of statements contained within a pair of braces.
k) A procedure for solving a problem in terms of the actions to execute and the order in which the actions
should execute.
l)
Arithmetic assignment operators.
m) Decrement operator.
n) Building blocks for more complicated types in Java.
o) Used when the number of repetitions is not known before the loop begins executing.
p) Empty statement.
q) Used when the number of repetitions is known before
the loop begins executing.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Prelab Activities
103
Name:
Fill in the Blank
Fill in the Blank
Name:
Date:
Section:
Fill in the blanks for each of the following statements:
18. Specifying the order in which statements execute in a computer program is called program control .
19. The if selection statement executes an indicated action only when the condition is true.
20. Top-down, stepwise refinement is a process for refining pseudocode by maintaining a complete representation of the program during each refinement.
21. Java requires all variables to have a type before they can be used in a program. For this reason, Java is referred
to as a(n) strongly typed language.
22. Java uses internationally recognized standards for both characters and floating-point numbers.
23. A(n) declaration specifies the type and name of a variable.
24. The if…else selection statement specifies separate actions to execute when the condition is true and
when the condition is false.
25. The ++ operator and the -- operator increment and decrement a variable by 1, respectively.
26. Unary cast operator ( double ) creates a temporary double-precision, floating-point copy of its operand.
27. A value that contains a fractional part is referred to as a floating-point number and is represented by the types
float or double .
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Prelab Activities
105
Name:
Short Answer
Short Answer
Name:
Date:
Section:
Answer the following questions in the space provided. Your answers should be concise; aim for two or three sentences.
28. Explain the purpose of a selection statement.
Selection statements choose among alternative actions in a program. They check for certain conditions in a program, and perform different tasks if those conditions are met.
29. Use pseudocode or a UML activity diagram to give an example of sequence control statements.
Add this grade into the running total
Add one to the grade counter
30. Describe the term “algorithm” and why pseudocode can help programmers develop algorithms.
An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which the
actions should execute. Pseudocode helps in the development of algorithms because it forces you to “think out”
a program during the design process, then you can translate the pseudocode into Java code.
31. Use pseudocode or a UML activity diagram to give an example of an if…else selection statement.
If student’s grade is greater than or equal to 60
Print “Passed”
Else
Print “Failed”
32. Explain the difference between the if selection statement and the if…else selection statement.
The if selection statement performs an indicated action only when the given condition evaluates to true, otherwise the action is skipped. The if…else selection statement allows an action to be performed when the condition is true, and a separate action if the condition is false.
33. Use pseudocode to give an example of a looping construct in which the number of repetitions is known in
advance.
While student counter is less than or equal to 10
Prompt the user to enter the next exam result
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
106
Control Statements: Part 1
Chapter4
Prelab Activities
Name:
Short Answer
Input the next exam result
Add the grade to the running total
Add one to student counter
34. Use pseudocode to give an example of a looping construct in which the number of repetitions is not known
in advance.
Prompt the user to enter the first grade
Input the first grade (possibly the sentinel)
While the user has not yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Prompt the user to enter the next grade
Input the next grade (possibly the sentinel)
35. Explain how repetition statements are used.
Repetition statements specify that an action (or set of actions) should be performed repeatedly while a condition
remains true.
36. Explain the difference between counter-controlled and sentinel-controlled repetition.
Counter-controlled repetition is used when the number of repetitions is known in advance. Sentinel-controlled
repetition is used when the number of repetitions is not known in advance. In this case, a sentinel value specifies
when the repetition should terminate.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Prelab Activities
107
Name:
Programming Output
Programming Output
Name:
Date:
Section:
For each of the given program segments, read the code and write the output in the space provided below each
program. [Note: Do not execute these programs on a computer.]
For questions 37–39 assume the following class definition:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Test2
{
public static void main( String args[] )
{
Scanner input = new Scanner();
int number1;
System.out.println( "Enter an integer:" );
number1 = input.nextInt();
if ( number1 % 2 == 0 )
System.out.println( "%d is even\n", number1 );
else
System.out.println( "%d is odd\n", number1 );
} // end main
} // end class Test2
37. What will be output by lines 11–14 if the user enters the integer 2 at line 9?
Your answer:
2 is even
38. What will be output by lines 11–14 if the user enters the integer 3 at line 9?
Your answer:
3 is odd
39. What will be the output if the following code is placed at line 10 of the preceding class definition? Assume
that the user enters 5.
1
number1 = number1 + 3;
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
108
Control Statements: Part 1
Chapter4
Prelab Activities
Name:
Programming Output
Your answer:
8 is even
40. What is output by the following program?
1
2
3
4
5
6
7
8
9
10
11
public class Grade
{
public static void main( String args[] )
{
int grade1 = 65;
int grade2 = 50;
System.out.println( grade1 >= 60 ? "Passed." : "Failed." );
System.out.println( grade2 >= 60 ? "Passed." : "Failed." );
} // end main
} // end class Grade
Your answer:
Passed
Failed
For questions 41–43, assume the following class declaration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Value
{
public static void main( String args[] )
{
int x;
int xLimit;
/* assign values to x and xLimit here */
while ( x <= xLimit )
{
x++;
System.out.printf( "The value of x is %d\n", x );
} // end while
System.out.printf( "The final value of x is %d\n", x );
} // end main
} // end class Value
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Prelab Activities
Name:
Programming Output
41. What will be the output if the following code is placed at line 8 of the class?
1
2
x = 1;
xLimit = 5;
Your answer:
The value of x is 2
The value of x is 3
The value of x is 4
The value of x is 5
The value of x is 6
The final value of x is 6
42. What will be the output if the following code is placed at line 8 of the class?
1
2
x = 1;
xLimit = -2;
Your answer:
The final value of x is 1
43. What will be the output if the following code is placed at line 8 of the class?
1
2
x = 10;
xLimit = 5;
Your answer:
The final value of x is 10
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
109
110
Control Statements: Part 1
Chapter4
Prelab Activities
Name:
Programming Output
For questions 44–46, assume the following class declaration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Value
{
public static void main( String args[] )
{
int x;
int xLimit;
/* assign values to x and xLimit here */
while ( x <= xLimit )
{
x++;
if ( x % 2 == 0 )
System.out.printf( "%d is even.\n", x );
else
System.out.printf( "%d is odd.\n", x );
} // end while
} // end main
} // end class Value
44. What will be the output if the following code is placed at line 8 of the class?
1
2
x = 0;
xLimit = 10;
Your answer:
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.
6 is even.
7 is odd.
8 is even.
9 is odd.
10 is even.
11 is odd.
45. What will be the output if the following code is placed at line 8 of the class?
1
2
x = 0
xLimit = -2;
Your answer:
(no output)
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Prelab Activities
Name:
Programming Output
46. What will be the output if the following code is placed at line 8 of the class?
1
2
x = 10;
xLimit = 5;
Your answer:
(no output)
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
111
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Prelab Activities
113
Name:
Correct the Code
Correct the Code
Name:
Date:
Section:
Determine if there is an error in each of the following program segments. If there is an error, specify whether it
is a logic error or a compilation error, circle the error in the program and write the corrected code in the space
provided after each problem. If the code does not contain an error, write “no error.” [Note: There may be more
than one error in each program segment.]
47. The following segment of code should calculate whether a student has a passing grade. If so, the code should
print "Passed." Otherwise, the code should print "Failed." and "You must take this course again."
1
2
3
4
5
if ( grade >= 60 )
System.out.println( "Passed." );
else
System.out.println( "Failed." );
System.out.println( "You must take this course again." );
Your answer:
1
2
3
4
5
6
7
if ( grade >= 60 )
System.out.println( "Passed." );
else
{
System.out.println( "Failed." );
System.out.println( "You must take this course again." );
}
•
Missing braces before line 4 and after line 5. Logic error.
48. The following while loop should compute the product of all the integers between 1 and 5, inclusive.
1
2
3
4
5
int i = 1;
int product = 1;
while ( i <= 5 );
product *= i;
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
114
Control Statements: Part 1
Chapter4
Prelab Activities
Name:
Correct the Code
Your answer:
1
2
3
4
5
6
7
8
int i = 1;
int product = 1;
while ( i <= 5 );
{
product *= i;
i++;
}
•
The value of variable i is not incremented in the while loop. Logic error.
•
The semicolon after the while loop’s header must be removed. Logic error.
49. The following while loop should print all the even integers between 0 and 20, inclusive.
1
2
3
4
5
6
7
8
int i = 0;
while ( i <= 20 )
if ( i % 2 = 0 )
System.out.printf( "%d ", i );
i++
Your answer:
1
2
3
4
5
6
7
8
9
int i = 0;
while ( i <= 20 )
{
if ( i % 2 = 0 )
System.out.printf( "%d ", i );
}
•
i++
Missing braces on lines 4 and 9. Variable i must be incremented within the while loop or the program
will enter an infinite loop. Logic error.
50. The following while loop should print the numbers 0 through 5, inclusive.
1
2
3
4
5
6
7
int i = 0;
while ( i < 5 )
{
System.out.printf( "%d ", i );
i++;
}
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Prelab Activities
115
Name:
Correct the Code
Your answer:
1
2
3
4
5
6
7
int i = 0;
while ( i <= 5 )
{
System.out.printf( "%d ", i );
i++;
}
•
The if statement on line 3 should use the <= operator. Otherwise, the loop will not print i when it is
equal to 5. Logic error.
51. The following while loop should print the even numbers from 20 down through 0, inclusive.
1
2
3
4
5
6
7
8
9
10
int i = 20;
while ( i >= 0 )
{
if ( i % 2 == 0 )
System.out.printf( "%d ", i );
}
i++;
Your answer:
1
2
3
4
5
6
7
8
9
10
int i = 20;
while ( i >= 0 )
{
if ( i % 2 == 0 )
System.out.printf( "%d ", i );
}
•
i--;
Variable i should be decremented on line 8. If the value is incremented, the program will enter an infinite loop. Logic error.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
116
Control Statements: Part 1
Chapter4
Prelab Activities
Name:
Correct the Code
52. The following while loop should print the sum of the integers between 0 and 5, inclusive.
1
2
3
4
5
6
7
8
9
int sum = 0;
while ( i <= 5 )
{
sum += i;
i++;
}
System.out.printf( "The sum is: %d\n", sum );
Your answer:
1
2
3
4
5
6
7
8
9
10
int sum = 0;
int i = 0;
while ( i <= 5 )
{
sum += i;
i++;
}
System.out.printf( "The sum is: %d\n", sum );
•
Variable i must be declared and initialized on line 2. Compilation error.
53. The following while loop should print the sum of the odd integers between 0 and 15, inclusive.
1
2
3
4
5
6
7
8
9
10
11
int sum = 0, i = 0;
while ( i < 15 )
{
if ( i % 2 != 0 )
sum += i;
}
i++;
System.out.printf( "The sum is: %d\n", sum );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Prelab Activities
117
Name:
Correct the Code
Your answer:
1
2
3
4
5
6
7
8
9
10
11
int sum = 0, i = 0;
while ( i <= 15 )
{
if ( i % 2 != 0 )
sum += i;
}
i++;
System.out.printf( "The sum is: %d\n", sum );
•
The while loop should use the <= operator on line 3 so that the loop runs when i is equal to 15. Logic
error.
54. The following while loop should print the product of the odd integers between 0 and 10, inclusive.
1
2
3
4
5
6
7
8
9
10
11
int product = 1, i = 0;
while ( i <= 10 )
{
if ( i % 2 != 0 )
i *= product;
}
product++;
System.out.printf( "The product is: %d\n", product );
Your answer:
1
2
3
4
5
6
7
8
9
10
11
int product = 1, i = 0;
while ( i <= 10 )
{
if ( i % 2 != 0 )
product *= i;
}
i++;
System.out.printf( "The product is: %d\n", product );
•
The program should multiply product by i during each iteration of the while loop. The while loop
should then increment i. Logic error.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
119
Lab Exercises
Lab Exercise 1 — Credit
Name:
Date:
Section:
The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. Description of the Problem
3. Sample Output
4. Program Template (Fig. L 4.1 and Fig. L 4.2)
5. Problem-Solving Tips
6. Follow-Up Questions and Activities
The program template represents a complete working Java program with one or more key lines of code replaced
with comments. Read the problem description and examine the sample output, then study the template code.
Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the
program. Compare your output with the sample output provided. Then answer the follow-up questions. The
source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.
Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 4 of Java How to Program: Seventh Edition. In this lab, you will practice:
•
Writing pseudocode.
•
Using selection statements.
The follow-up questions and activities also will give you practice:
•
Using counter-controlled repetition.
Description of the Problem
Develop a Java application that will determine whether any of several department-store customers has exceeded
the credit limit on a charge account. For each customer, the following facts are available:
a) account number
b) balance at the beginning of the month
c) total of all items charged by the customer this month
d) total of all credits applied to the customer’s account this month
e) allowed credit limit.
The program should input all of these facts as integers, calculate the new balance (= beginning balance + charges
– credits), display the new balance and determine whether the new balance exceeds the customer’s credit limit.
For those customers whose credit limit is exceeded, the program should display the message "Credit limit
exceeded".
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
120
Control Statements: Part 1
Chapter4
Lab Exercises
Name:
Lab Exercise 1 — Credit
Sample Output
Enter Account Number (or -1 to quit): 1
Enter Balance: 100
Enter Charges: 80
Enter Credits: 25
Enter Credit Limit: 200
New balance is 155
Enter Account Number (or -1 to quit): 2
Enter Balance: 450
Enter Charges: 240
Enter Credits: 300
Enter Credit Limit: v
New balance is 390
Enter Account Number (or -1 to quit): 3
Enter Balance: 500
Enter Charges: 300
Enter Credits: 125
Enter Credit Limit: 400
New balance is 675
Credit limit exceeded
Enter Account Number (or -1 to quit): -1
Program Template
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Lab 1: Credit.java
// Program monitors accounts.
import java.util.Scanner;
public class Credit
{
// calculates the balance on several credit accounts
public void calculateBalance()
{
Scanner input = new Scanner( System.in );
Fig. L 4.1 |
int
int
int
int
int
int
account; // account number
oldBalance; // starting balance
charges; // total charges
credits; // total credits
creditLimit; // allowed credit limit
newBalance; // new balance
System.out.print( "Enter Account Number (or -1 to quit): " );
/* write code to input an integer and store it in account */
/* write code to loop while the account number is not -1 */
/* write code to input the rest of the customer information. */
/* write code to compute the new balance */
Credit.java.
(Part 1 of 2.)
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
121
Name:
Lab Exercise 1 — Credit
28
29
30
31
32
33
34
/* write code that will check if the new balance is greater than the
credit limit and output the proper information */
/* write code to input a new account number and close the while loop. */
} // end method calculateBalance
} // end class Credit
Fig. L 4.1 |
1
2
3
4
5
6
7
8
9
10
Credit.java.
(Part 2 of 2.)
// Lab 1: CreditTest.java
// Test application for class Credit
public class CreditTest
{
public static void main(String args[])
{
Credit application = new Credit();
application.calculateBalance();
} // end main
} // end class CreditTest
Fig. L 4.2 |
CreditTest.java
Problem-Solving Tips
1. There are five input values required. But the account number must be input before the loop in order to
test whether it is equal to the sentinel value. So there should be six input statements, five in the loop
and one before it.
2. Use the formula given in the problem description to compute the new balance.
3. Use an if statement to determine whether newBalance is larger than the customer’s creditLimit. If so,
indicate that the credit limit was exceeded.
4. Write out your algorithms in pseudocode before writing any code.
5. Be sure to follow the spacing and indentation conventions mentioned in the text.
6. If you have any questions as you proceed, ask your lab instructor for assistance.
Solution
Top:
Determine if each of an arbitrary number of department store customers has exceeded the credit limit on a
charge account.
First refinement:
Input the account number, beginning balance, total charges, total credits, and credit limit for a customer, calculate the customer’s new balance and determine if the balance exceeds the credit limit. Then process the next
customer.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
122
Control Statements: Part 1
Chapter4
Lab Exercises
Name:
Lab Exercise 1 — Credit
Second refinement:
Input the first customer’s account number
While the sentinel value (-1) has not been entered for the account number
Input the customer’s beginning balance
Input the customer’s total charges
Input the customer’s total credits
Input the customer’s credit limit
Calculate the customer’s new balance
Print the new balance
If the balance exceeds the credit limit
Print "Credit Limit Exceeded"
Input the next customer’s account number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Lab 1: Credit.java
// Program monitors accounts.
import java.util.Scanner;
public class Credit
{
// calculates the balance on several credit accounts
public void calculateBalance()
{
Scanner input = new Scanner( System.in );
int
int
int
int
int
int
account; // account number
oldBalance; // starting balance
charges; // total charges
credits; // total credits
creditLimit; // allowed credit limit
newBalance; // new balance
System.out.print( "Enter Account Number (or -1 to quit): " );
account = input.nextInt(); // read in account number
// exit if the input is -1 otherwise, proceed with the program
while ( account != -1 )
{
System.out.print( "Enter Balance: " );
oldBalance = input.nextInt(); // read in original balance
System.out.print( "Enter Charges: " );
charges = input.nextInt(); // read in charges
System.out.print( "Enter Credits: " );
credits = input.nextInt(); // read in credits
System.out.print( "Enter Credit Limit: " );
creditLimit = input.nextInt(); // read in credit limit
// calculate and display new balance
newBalance = oldBalance + charges - credits;
System.out.printf( "New balance is %d\n", newBalance );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
Name:
Lab Exercise 1 — Credit
40
41
42
43
44
45
46
47
48
49
System.out.print( "\nEnter Account Number (or -1 to quit): " );
account = input.nextInt(); // read in next account number
} // end while
} // end method calculateBalance
} // end class Credit
1
2
3
4
5
6
7
8
9
10
// Lab 1: CreditTest.java
// Test application for class Credit
public class CreditTest
{
public static void main(String args[])
{
Credit application = new Credit();
application.calculateBalance();
} // end main
} // end class CreditTest
// display a warning if the user has exceed the credit limit
if ( newBalance > creditLimit )
System.out.println( "Credit limit exceeded" );
Follow-Up Questions and Activities
1. Modify the program to use counter-controlled repetition to process 10 accounts.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Lab 1: Credit.java
// Program monitors accounts.
import java.util.Scanner;
public class Credit
{
// calculates the balance on several credit accounts
public void calculateBalance()
{
Scanner input = new Scanner( System.in );
int
int
int
int
int
int
int
account; // account number
oldBalance; // starting balance
charges; // total charges
credits; // total credits
creditLimit; // allowed credit limit
newBalance; // new balance
count = 0; // number of accounts entered
// exit if the input is -1 otherwise, proceed with the program
while ( count < 10 )
{
System.out.print( "\nEnter Account Number: " );
account = input.nextInt(); // read in account number
System.out.print( "Enter Balance: " );
oldBalance = input.nextInt(); // read in original balance
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
123
124
Control Statements: Part 1
Chapter4
Lab Exercises
Name:
Lab Exercise 1 — Credit
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
count++; // increment number of accounts input
} // end while
} // end method calculateBalance
} // end class Credit
1
2
3
4
5
6
7
8
9
10
// Lab 1: CreditTest.java
// Test application for class Credit
public class CreditTest
{
public static void main(String args[])
{
Credit application = new Credit();
application.calculateBalance();
} // end main
} // end class CreditTest
System.out.print( "Enter Charges: " );
charges = input.nextInt(); // read in charges
System.out.print( "Enter Credits: " );
credits = input.nextInt(); // read in credits
System.out.print( "Enter Credit Limit: " );
creditLimit = input.nextInt(); // read in credit limit
// calculate and display new balance
newBalance = oldBalance + charges - credits;
System.out.printf( "New balance is %d\n", newBalance );
// display a warning if the user has exceed the credit limit
if ( newBalance > creditLimit )
System.out.println( "Credit limit exceeded" );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
Name:
Lab Exercise 1 — Credit
Enter Account Number: 1
Enter Balance: 100
Enter Charges: 80
Enter Credits: 25
Enter Credit Limit: 200
New balance is 155
Enter Account Number: 2
Enter Balance: 450
Enter Charges: 240
Enter Credits: 300
Enter Credit Limit: 600
New balance is 390
Enter Account Number: 3
Enter Balance: 500
Enter Charges: 300
Enter Credits: 125
Enter Credit Limit: 400
New balance is 675
Credit limit exceeded
Enter Account Number: 4
Enter Balance: 0
Enter Charges: 350
Enter Credits: 0
Enter Credit Limit: 375
New balance is 350
Enter Account Number: 5
Enter Balance: 200
Enter Charges: 300
Enter Credits: 200
Enter Credit Limit: 250
New balance is 300
Credit limit exceeded
Enter Account Number: 8
Enter Balance: 250
Enter Charges: 50
Enter Credits: 200
Enter Credit Limit: 250
New balance is 100
Enter Account Number: 9
Enter Balance: 500
Enter Charges: 100
Enter Credits: 300
Enter Credit Limit: 300
New balance is 300
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
125
126
Control Statements: Part 1
Chapter4
Lab Exercises
Name:
Lab Exercise 1 — Credit
Enter Account Number: 10
Enter Balance: 75
Enter Charges: 240
Enter Credits: 125
Enter Credit Limit: 200
New balance is 190
2. Modify the program to use counter-controlled repetition to process the number of accounts specified by the
user. The number of accounts should be input before processing any account information.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Lab 1: Credit.java
// Program monitors accounts.
import java.util.Scanner;
public class Credit
{
// calculates the balance on several credit accounts
public void calculateBalance()
{
Scanner input = new Scanner( System.in );
int
int
int
int
int
int
int
int
account; // account number
oldBalance; // starting balance
charges; // total charges
credits; // total credits
creditLimit; // allowed credit limit
newBalance; // new balance
count = 0; // number of accounts entered
number; // number of accounts for user to enter
System.out.print( "Enter Number of Accounts: " );
account = input.nextInt(); // read in number of accounts
// exit if the input is -1 otherwise, proceed with the program
while ( count < number )
{
System.out.print( "Enter Account Number: " );
account = input.nextInt(); // read in account number
System.out.print( "Enter Balance: " );
oldBalance = input.nextInt(); // read in original balance
System.out.print( "Enter Charges: " );
charges = input.nextInt(); // read in charges
System.out.print( "Enter Credits: " );
credits = input.nextInt(); // read in credits
System.out.print( "Enter Credit Limit: " );
creditLimit = input.nextInt(); // read in credit limit
// calculate and display new balance
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
Name:
Lab Exercise 1 — Credit
43
44
45
46
47
48
49
50
51
52
53
count++; // increment number of accounts input
} // end while
} // end method calculateBalance
} // end class Credit
1
2
3
4
5
6
7
8
9
10
// Lab 1: CreditTest.java
// Test application for class Credit
public class CreditTest
{
public static void main(String args[])
{
Credit application = new Credit();
application.calculateBalance();
} // end main
} // end class CreditTest
newBalance = oldBalance + charges - credits;
System.out.printf( "New balance is %d\n", newBalance );
// display a warning if the user has exceed the credit limit
if ( newBalance > creditLimit )
System.out.println( "Credit limit exceeded" );
Enter Number of Accounts: 3
Enter Account Number: 1
Enter Balance: 100
Enter Charges: 80
Enter Credits: 25
Enter Credit Limit: 200
New balance is 155
Enter Account Number: 2
Enter Balance: 450
Enter Charges: 240
Enter Credits: 300
Enter Credit Limit: 600
New balance is 390
Enter Account Number: 3
Enter Balance: 500
Enter Charges: 300
Enter Credits: 125
Enter Credit Limit: 400
New balance is 675
Credit limit exceeded
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
127
128
Control Statements: Part 1
Chapter4
Lab Exercises
Name:
Lab Exercise 1 — Credit
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
129
Name:
Lab Exercise 2 — Palindromes
Lab Exercise 2 — Palindromes
Name:
Date:
Section:
The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. Description of the Problem
3. Sample Output
4. Program Template (Fig. L 4.3 and Fig. L 4.4)
5. Problem Solving Tips
6. Follow-Up Question and Activity
The program template represents a complete working Java program with one or more key lines of code replaced
with comments. Read the problem description and examine the sample output, then study the template code.
Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the
program. Compare your output with the sample output provided. Then answer the follow-up question. The
source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.
Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 4 of Java How to Program: Seventh Edition. In this lab you will practice:
•
Using selection statements.
•
Using sentinel-controlled repetition.
•
Using if…else selection statements.
The follow-up question and activity will also give you practice:
•
Modifying existing code to perform a similar task.
Description of the Problem
A palindrome is a sequence of characters that reads the same backward as forward. For example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611. Write an application that reads in
a five-digit integer and determines whether it is a palindrome. If the number is not five digits long, display an
error message and allow the user to enter a new value.
Sample Output
Enter a 5-digit number: 1234
Number must be 5 digits
Enter a 5-digit number: 123456
Number must be 5 digits
Enter a 5-digit number: 54345
54345 is a palindrome!!!
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
130
Control Statements: Part 1
Chapter4
Lab Exercises
Name:
Lab Exercise 2 — Palindromes
Program Template
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Lab 2: Palindrome.java
// Program tests for a palindrome
import java.util.Scanner;
public class Palindrome
{
// checks if a 5-digit number is a palindrome
public void checkPalindrome()
{
Scanner input = new Scanner( System.in );
int
int
int
int
int
int
//
//
//
//
//
//
user input number
first digit
second digit
fourth digit
fifth digit
number of digits in input
number = 0;
digits = 0;
/* Write code that inputs a five-digit number. Display an error message
if the number is not five digits. Loop until a valid input is received. */
/* Write code that separates the digits in the five digit number. Use
division to isolate the left-most digit in the number, use a remainder
calculation to remove that digit from the number. Then repeat this
process. */
/* Write code that determines whether the first and last digits are
identical and the second and Fourth digits are identical. Output
whether or not the original string is a palindrome. */
} // end method checkPalindrome
} // end class Palindrome
Fig. L 4.3 |
1
2
3
4
5
6
7
8
9
10
number;
digit1;
digit2;
digit4;
digit5;
digits;
Palindrome.java.
// Lab 2: PalindromeTest.java
// Test application for class Palindrome
public class PalindromeTest
{
public static void main( String args[] )
{
Palindrome application = new Palindrome();
application.checkPalindrome();
} // end main
} // end class PalindromeTest
Fig. L 4.4 |
PalindromeTest.java
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
Name:
Lab Exercise 2 — Palindromes
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Lab 2: Palindrome.java
// Program tests for a palindrome
import java.util.Scanner;
public class Palindrome
{
// checks if a 5-digit number is a palindrome
public void checkPalindrome()
{
Scanner input = new Scanner( System.in );
int
int
int
int
int
int
number;
digit1;
digit2;
digit4;
digit5;
digits;
//
//
//
//
//
//
user input number
first digit
second digit
fourth digit
fifth digit
number of digits in input
number = 0;
digits = 0;
// Ask for a number until it is five digits
while ( digits != 5 )
{
System.out.print( "Enter a 5-digit number: " );
number = input.nextInt();
if ( number < 100000 )
{
if ( number > 9999 )
digits = 5;
else
System.out.println( "Number must be 5 digits" );
} // end if
else
System.out.println( "Number must be 5 digits" );
} // end while loop
// get
digit1
digit2
digit4
digit5
the digits
= number /
= number %
= number %
= number %
10000;
10000 / 1000;
10000 % 1000 % 100 / 10;
10000 % 1000 % 100 % 10;
// print whether the number is a palindrome
System.out.print( number );
if ( digit1 == digit5 )
{
if ( digit2 == digit4 )
System.out.println( " is a palindrome!!!" );
else
System.out.println( " is not a palindrome." );
}
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
131
132
Control Statements: Part 1
Chapter4
Lab Exercises
Name:
Lab Exercise 2 — Palindromes
55
56
57
58
else
System.out.println( " is not a palindrome." );
} // end method checkPalindrome
} // end class Palindrome
1
2
3
4
5
6
7
8
9
10
// Lab 2: PalindromeTest.java
// Test application for class Palindrome
public class PalindromeTest
{
public static void main( String args[] )
{
Palindrome application = new Palindrome();
application.checkPalindrome();
} // end main
} // end class PalindromeTest
Problem-Solving Tips
1. Determine the number of digits in the value input by the user and assign the result to digits. Use a
while loop to determine whether the user input contains the proper number of digits. In the condition,
determine whether digits is equal to five. If not, input a new value from the user and determine whether the new value contains the proper number of digits. When the number of digits is five, the loop
should terminate.
2. Use division and remainder calculations to obtain the separate digits. For a five-digit number to be a
palindrome, the first and fifth digits must be the same and the second and fourth digits must be the
same.
3. Be sure to follow the spacing and indentation conventions mentioned in the text.
4. If you have any questions as you proceed, ask your lab instructor for assistance.
Follow-Up Question and Activity
1. Modify the program to determine whether a seven-digit number is a palindrome.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Lab 2: Palindrome.java
// Program tests for a palindrome
import java.util.Scanner;
public class Palindrome
{
// checks if a 5-digit number is a palindrome
public void checkPalindrome()
{
Scanner input = new Scanner( System.in );
int
int
int
int
int
int
number;
digit1;
digit2;
digit3;
digit5;
digit6;
//
//
//
//
//
//
user input number
first digit
second digit
third digit
fifth digit
sixth digit
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
Name:
Lab Exercise 2 — Palindromes
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
1
2
3
4
5
6
int digit7; // seventh digit
int digits; // number of digits in input
number = 0;
digits = 0;
// Ask for a number until it is seven digits
while ( digits != 7 )
{
System.out.print( "Enter a 7-digit number: " );
number = input.nextInt();
if ( number < 10000000 )
{
if ( number > 999999 )
digits = 7;
else
System.out.println( "Number must be 7 digits" );
} // end if
else
System.out.println( "Number must be 7 digits" );
} // end while loop
// get
digit1
digit2
digit3
digit5
digit6
digit7
the digits
= number /
= number %
= number %
= number %
= number %
= number %
1000000;
1000000 / 100000;
100000 / 10000;
1000 / 100;
100 / 10;
10;
// print whether the number is a palindrome
System.out.print( number );
if ( digit1 == digit7 )
{
if ( digit2 == digit6 )
{
if ( digit3 == digit5 )
System.out.println( " is a palindrome!!!" );
else
System.out.println( " is not a palindrome." );
}
else
System.out.println( " is not a palindrome." );
}
else
System.out.println( " is not a palindrome." );
} // end method checkPalindrome
} // end class Palindrome
// Lab 2: PalindromeTest.java
// Test application for class Palindrome
public class PalindromeTest
{
public static void main( String args[] )
{
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
133
134
Control Statements: Part 1
Chapter4
Lab Exercises
Name:
Lab Exercise 2 — Palindromes
7
8
9
10
Palindrome application = new Palindrome();
application.checkPalindrome();
} // end main
} // end class PalindromeTest
Enter a 7-digit number: 7654567
7654567 is a palindrome!!!
Enter a 7-digit number: 7654321
7654321 is not a palindrome.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
135
Name:
Lab Exercise 3 — Largest Number
Lab Exercise 3 — Largest Number
Name:
Date:
Section:
The following problem is intended to be solved in a closed-lab session with a teaching assistant or instructor
present. The problem is divided into six parts:
1. Lab Objectives
2. Description of the Problem
3. Sample Output
4. Program Template (Fig. L 4.5 and Fig. L 4.6)
5. Problem-Solving Tips
6. Follow-Up Question and Activity
The program template represents a complete working Java program with one or more key lines of code replaced
with comments. Read the problem description and examine the sample output, then study the template code.
Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the
program. Compare your output with the sample output provided. Then answer the follow-up question. The
source code for the template is available at www.deitel.com/books/jhtp7/ and www.prenhall.com/deitel.
Lab Objectives
This lab was designed to reinforce programming concepts from Chapter 4 of Java How to Program: Seventh Edition. In this lab you will practice:
•
Using while statements
•
Using counter-controlled repetition
•
Using if statements
The follow-up question and activity also will give you practice:
•
Using if…else statements.
Description of the Problem
The process of finding the largest value (i.e., the maximum of a group of values) is used frequently in computer
applications. For example, a program that determines the winner of a sales contest would input the number of
units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocode
program and then a Java application that inputs a series of 10 integers and determines and prints the largest integer. Your program should use at least the following three variables:
a)
counter:
A counter to count to 10 (i.e., to keep track of how many numbers have been input and to
determine when all 10 numbers have been processed).
b)
number:
c)
largest:
The integer most recently input by the user.
The largest number found so far.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
136
Control Statements: Part 1
Lab Exercises
Chapter4
Name:
Lab Exercise 3 — Largest Number
Sample Output
Enter number: 56
Enter number: -10
Enter number: 200
Enter number: 25
Enter number: 8
Enter number: 500
Enter number: -20
Enter number: 678
Enter number: 345
Enter number: 45
Largest number is 678
Program Template
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Lab 3: Largest.java
// Program determines and prints the largest of ten numbers.
import java.util.Scanner;
public class Largest
{
// determine the largest of 10 numbers
public void determineLargest()
{
Scanner input = new Scanner( System.in );
int largest; // largest number
int number; // user input
int counter; // number of values entered
/* write code to get the first integer and store it in variable largest */
/* write code to initialize the number of integers entered */
/* write code to loop until 10 numbers are entered */
/* write code to prompt the user to enter a number and read tat number */
/* write code to test whether the number entered is greater than the largest
if so, replace the value of largest with the entered number */
/* write code to increment the number of integers entered */
System.out.printf( "Largest number is %d\n", largest );
} // end method determineLargest
} // end class Largest
Fig. L 4.5 |
Largest.java
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
137
Name:
Lab Exercise 3 — Largest Number
1
2
3
4
5
6
7
8
9
10
// Lab 3: LargestTest.java
// Test application for class Largest
public class LargestTest
{
public static void main( String args[] )
{
Largest application = new Largest();
application.determineLargest();
} // end main
} // end class LargestTest
Fig. L 4.6 |
LargestTest.java
Problem-Solving Tips
1. Remember to initialize the count of the number of integers entered.
2. Use an if statement to test whether the number input from the user is larger than the largest number
you have stored.
3. Be sure to follow the spacing and indentation conventions mentioned in the text.
4. If you have any questions as you proceed, ask your lab instructor for assistance.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Lab 3: Largest.java
// Program determines and prints the largest of ten numbers.
import java.util.Scanner;
public class Largest
{
// determine the largest of 10 numbers
public void determineLargest()
{
Scanner input = new Scanner( System.in );
int largest; // largest number
int number; // user input
int counter; // number of values entered
// get first number and assign it to variable largest
System.out.print( "Enter number: " );
largest = input.nextInt();
counter = 1;
// get rest of the numbers and find the largest
while ( counter < 10 )
{
System.out.print( "Enter number: " );
number = input.nextInt();
if ( number > largest )
largest = number;
counter++;
} // end while loop
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
138
Control Statements: Part 1
Lab Exercises
Chapter4
Name:
Lab Exercise 3 — Largest Number
33
34
35
36
System.out.printf( "Largest number is %d\n", largest );
} // end method determineLargest
} // end class Largest
1
2
3
4
5
6
7
8
9
10
// Lab 3: LargestTest.java
// Test application for class Largest
public class LargestTest
{
public static void main( String args[] )
{
Largest application = new Largest();
application.determineLargest();
} // end main
} // end class LargestTest
Follow-Up Question and Activity
1. Modify the program to find the two largest values of the 10 values entered.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Lab 3: TwoLargest.java
// Program determines and prints the two largest of ten numbers.
import java.util.Scanner;
public class TwoLargest
{
// determine the two largest of 10 integers
public void determineTwoLargest()
{
Scanner input = new Scanner( System.in );
int
int
int
int
largest; // largest number
nextLargest; // second largest number
number; // user input
counter; // number of values entered
// get first number and assign it to variable largest
System.out.print( "Enter number: " );
largest = input.nextInt();
// get second number and compare it with first number
System.out.print( "Enter number: " );
number = input.nextInt();
if ( number > largest )
{
nextLargest = largest;
largest = number;
} // end if
else
nextLargest = number;
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
Name:
Lab Exercise 3 — Largest Number
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
System.out.printf( "Largest number is %d\nSecond largest number is %d\n",
largest, nextLargest );
} // end method determineTwoLargest
} // end class TwoLargest
1
2
3
4
5
6
7
8
9
10
// Lab 3: TwoLargestTest.java
// Test application for class TwoLargest
public class TwoLargestTest
{
public static void main( String args[] )
{
TwoLargest application = new TwoLargest();
application.determineTwoLargest();
} // end main
} // end class TwoLargestTest
counter = 2;
// get rest of the numbers and find the largest and nextLargest
while ( counter < 10 )
{
System.out.print( "Enter number: " );
number = input.nextInt();
if ( number > largest ) {
nextLargest = largest;
largest = number;
} // end if
else if ( number > nextLargest )
nextLargest = number;
counter++;
} // end while loop
Enter number: 56
Enter number: -10
Enter number: 200
Enter number: 25
Enter number: 8
Enter number: 500
Enter number: -20
Enter number: 678
Enter number: 345
Enter number: 45
Largest number is 678
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
139
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
141
Name:
Debugging
Debugging
Name:
Date:
Section:
The program in this section does not run properly. Fix all the compilation errors, so that the program will compile successfully. Once the program compiles, compare the output to the sample output, and eliminate any logic
errors that exist. The sample output demonstrates what the program’s output should be once the program’s code
is corrected. The file is available at www.deitel.com/books/jhtp7/ and at www.prenhall.com/deitel.
Sample Output
1 for Fahrenheit to Celsius
2 for Celsius to Fahrenheit
3 to quit:
1
Enter the degrees in Fahrenheit:
212
The temp in Celsius is 100
1 for Fahrenheit to Celsius
2 for Celsius to Fahrenheit
3 to quit:
2
Enter the degrees in Celsius:
100
The temp in Fahrenheit is 212
1 for Fahrenheit to Celsius
2 for Celsius to Fahrenheit
3 to quit:
3
Broken Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Chapter 4 of Java How To Program
// Debugging Problem
import java.util.Scanner;
public class Temperature
{
public static void main( String args[] )
{
int option;
int degree1;
int celsius1;
int fahrenheit1;
Fig. L 4.7
Scanner input = new Scanner( System.in );
option = 0;
| Temperature.java.
(Part 1 of 2.)
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
142
Control Statements: Part 1
Chapter4
Lab Exercises
Name:
Debugging
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
While ( option != 3 )
System.out.printf( "%s\n%s\n%s\n", "1 for Fahrenheit to Celsius",
"2 for Celsius to Fahrenheit", "3 to quit:" );
option = input.nextDouble();
System.out.println( "Enter the degrees in Fahrenheit: " );
degree1 = input.nextDouble();
celsius1 = ( degree1 - 32 ) * 5 / 9;
System.out.printf( "The temp in Celsius is %d\n", celsius1 );
if ( option == 2 );
System.out.println( "Enter the degrees in Celsius: " );
degree1 = input.nextDouble();
fahrenheit1 = ( degree1 * 9 / 5 ) + 32;
System.out.printf( "The temp in Fahrenheit is %d\n", fahrenheit1 );
} // end while loop
} // end method Main
} // end class Temperature
Fig. L 4.7
| Temperature.java.
(Part 2 of 2.)
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Chapter 4 of Java How To Program
// Debugging Problem
import java.util.Scanner;
public class Temperature
{
public static void main( String args[] )
{
int option;
int degree1;
int celsius1;
int fahrenheit1;
Scanner input = new Scanner( System.in );
option = 0;
while ( option != 3 )
{
System.out.printf( "%s\n%s\n%s\n", "1 for Fahrenheit to Celsius",
"2 for Celsius to Fahrenheit", "3 to quit:" );
option = input.nextInt();
if ( option == 1 )
{
System.out.println( "Enter the degrees in Fahrenheit: " );
degree1 = input.nextInt();
}
celsius1 = ( degree1 - 32 ) * 5 / 9;
System.out.printf( "The temp in Celsius is %d\n", celsius1 );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Lab Exercises
143
Name:
Debugging
32
33
34
35
36
37
38
39
40
41
42
else if ( option == 2 )
{
System.out.println( "Enter the degrees in Celsius: " );
degree1 = input.nextInt();
fahrenheit1 = ( degree1 * 9 / 5 ) + 32;
System.out.printf( "The temp in Fahrenheit is %d\n", fahrenheit1 );
}
} // end while loop
} // end method Main
} // end class Temperature
List of Errors
•
Keyword while is spelled with a an uppercase “W” on line 18, which is compilation error.
•
The while statement is missing an opening brace on line 19.
•
An if…else statement testing for option equal to 1
else part has been added to the beginning of line 30.
•
Opening (lines 23 and 31) and closing (lines 29 and 37) braces are left out in the if…else statement
which leads to either a compilation or logic error.
•
The if statement (line 30) has a semicolon after the condition which leads to a logic error.
•
The program should use Scanner method nextInt instead of method nextDouble on lines 25 and 33
to input an integer from the user.
is omitted. It has been added to line 24 and the
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
145
Postlab Activities
Coding Exercises
Name:
Date:
Section:
These coding exercises reinforce the lessons learned in the lab and provide additional programming experience
outside the classroom and laboratory environment. They serve as a review after you have successfully completed
the Prelab Activities and Lab Exercises.
For each of the following problems, write a program or a program segment that performs the specified action.
1. Write a Java application that inputs an integer and uses an if statement to determine whether the integer is
even and, if it is, prints that number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Test2
{
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
int number1;
System.out.print( "Enter an integer: " );
number1 = input.nextInt();
if ( number1 % 2 == 0 )
System.out.println( number1 );
} // end main
} // end class Test2
Enter an integer: 8
8
2. Write a Java application that inputs an integer and uses an if…else statement to determine whether the
integer is odd or even. If it is odd, print the number followed by "is odd"; if it is even, print the number
followed by "is even".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Test2
{
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
int number1;
System.out.print( "Enter an integer: " );
number1 = input.nextInt();
if ( number1 % 2 == 0 )
System.out.printf( "%d is even\n", number1 );
else
System.out.printf( "%d is odd\n", number1 );
} // end main
} // end class Test2
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
146
Control Statements: Part 1
Chapter4
Postlab Activities
Name:
Coding Exercises
Enter an integer: 7
7 is odd
3. Rewrite your solution to Coding Exercise 2 so that it uses the conditional operator (?:), rather than an
if…else statement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Test2
{
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
int number1;
System.out.print( "Enter an integer: " );
number1 = input.nextInt();
System.out.printf( "%d is %s\n", number1,
( ( number1 % 2 == 0 ) ? "even" : "odd" ) );
} // end main
} // end class Test2
Enter an integer: 7
7 is odd
4. Write a Java application that uses a counter-controlled loop to sum the integers in the range 1–10, then compute the average of those numbers (as an integer value). Display the sum and the average.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Test2
{
// main method begins execution of Java application
public static void main( String args[] )
{
int count = 0;
int numbers = 1;
while ( numbers < 11 )
{
count += numbers;
numbers++;
}
System.out.printf( "The sum of the first ten integers is %d\n", count );
System.out.printf( "The average of the first ten integers is %d\n", count / 10 );
} // end method main
} // end class average
The sum of the first ten integers is 55
The average of the first ten integers is 5
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 4
Control Statements: Part 1
Postlab Activities
Name:
Coding Exercises
5. Modify your solution to Coding Exercise 4 so that a user can specify the range of numbers to average.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.Scanner;
public class Test2
{
// main method begins execution of Java application
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
int count = 0;
int numbers;
int max;
int range;
System.out.print( "Please enter the low end of the range of numbers: " );
numbers = input.nextInt();
System.out.print( "Please enter the high end of the range of numbers: " );
max = input.nextInt();
range = max - numbers;
while ( numbers < max )
{
count += numbers;
numbers++;
}
System.out.printf( "The sum of the integers is %d\n", count );
System.out.printf( "The average of the integers is %d\n", count / range );
} // end method main
} // end class average
Please enter the low end of the range of numbers: 5
Please enter the high end of the range of numbers: 10
The sum of the integers is 35
The average of the integers is 7
6. Write a Java application that uses a loop to read in 10 numbers and calculates and prints their sum.
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.Scanner;
public class Test2
{
// main method begins execution of Java application
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
int counter = 0;
int number = 1;
int sum = 0;
System.out.println( "Please enter ten integers" );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
147
148
Control Statements: Part 1
Chapter4
Postlab Activities
Name:
Coding Exercises
14
15
16
17
18
19
20
21
22
23
24
25
while ( counter < 10 )
{
number = input.nextInt();
sum += number;
counter++;
}
System.out.printf( "The sum of the first ten integers is %d\n", sum );
System.out.printf( "The average of the first ten integers is %d\n", sum / 10 );
} // end method main
} // end class average
Please enter ten integers
2
4
6
8
10
12
14
16
18
20
The sum of the first ten integers is 110
The average of the first ten integers is 11
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.