1. 程式人生 > >JHTP練習題及課題_第四章_控制語句Part 1-賦值、++、--運算子

JHTP練習題及課題_第四章_控制語句Part 1-賦值、++、--運算子



Exercises

4.10 Compare andcontrast the if single-selection statement and the while repetitionstatement.

How are these twostatements similar? How are they different?

4.11 Explain whathappens when a Java program attempts to divide one integer by another.

What happens to thefractional part of the calculation? How can you avoid that outcome?

4.12 Describe thetwo ways in which control statements can be combined.

4.13 What type ofrepetition would be appropriate for calculating the sum of the first 100 positiveintegers? What type would be appropriate for calculating the sum of anarbitrary number of positive integers? Briefly describe how each of these taskscould be performed.

4.14 What is thedifference between preincrementing and postincrementing a variable?

4.15 Identify andcorrect the errors in each of the following pieces of code. [Note: There may be morethan one error in each piece of code.]

a) if (age >=65);

System.out.println("Ageis greater than or equal to 65"

);

else

System.out.println("Ageis less than 65)";

b) int x = 1, total;

while (x <= 10)

{

total += x;

++x;

}

c) while (x <= 100)

total += x;

++x;

d) while (y > 0)

{

System.out.println(y);

++y;

4.16 What does thefollowing program print?

1 //Exercise 4.16: Mystery.java

2 publicclass Mystery

3 {

4 publicstatic void main(String[] args)

5 {

6 int x = 1;

7 int total = 0;

8

9 while (x <= 10)

10 {

11 int y = x * x;

12 System.out.println(y);

13 total +=y;

14 ++x;

15 }

16

17 System.out.printf("Totalis %d%n", total);

18 }

19 } // endclass Mystery

For Exercise4.17 through Exercise 4.20, perform each of the following steps:

a) Read the problemstatement.

b) Formulate thealgorithm using pseudocode and top-down, stepwise refinement.

c) Write a Java program.

d) Test, debug andexecute the Java program.

e) Process three completesets of data.

4.17 (GasMileage) Drivers are concerned with the mileage their automobiles get.One driver has kept track of several trips by recording the miles driven andgallons used for each tankful. Develop a Java application that will input themiles driven and gallons used (both as integers) for each trip.

The program shouldcalculate and display the miles per gallon obtained for each trip and print thecombined miles per gallon obtained for all trips up to this point. Allaveraging calculations should produce floating-point results. Use class Scanner andsentinel-controlled repetition to obtain the data from the user.

4.18 (CreditLimit Calculator) Develop a Java application that determines whether any of several

department-storecustomers has exceeded the credit limit on a charge account. For each customer,the following facts are available:

a) account number

b) balance at thebeginning of the month

c) total of all itemscharged by the customer this month

d) total of all creditsapplied to the customer’s account this month

e) allowed credit limit.

The program should inputall these facts as integers, calculate the new balance (= beginning balance +charges – credits), display the new balance and determine whether the new balanceexceeds the customer’s credit limit. For those customers whose credit limit isexceeded, the program should displaythe message "Creditlimit exceeded".

4.19 (SalesCommission Calculator) A large company pays its salespeople on a commission basis.

The salespeople receive$200 per week plus 9% of their gross sales for that week. For example, a

salesperson who sells$5,000 worth of merchandise in a week receives $200 plus 9% of $5000, or a

total of $650. You’vebeen supplied with a list of the items sold by each salesperson. The values of

these items are asfollows:

Item Value

1 239.99

2 129.75

3 99.95

4 350.89

Develop a Javaapplication that inputs one salesperson’s items sold for last week andcalculates and

Commission=sum(itemsSold*itemValue)*(1+0.09)

displays thatsalesperson’s earnings. There’s no limit to the number of items that can besold.

4.20 (SalaryCalculator) Develop a Java application that determines the gross pay foreach of three employees. The company pays straight time for the first 40 hoursworked by each employee and time and a half for all hours worked in excess of40. You’re given a list of the employees, their number of hours worked lastweek and their hourly rates. Your program should input this information foreach employee, then determine and display the employee’s gross pay. Use class Scanner to input thedata.

Algorithm:

  1. If (workHours<40)

  2. Salary=workHours*hourlyRate;

  3. else

  4. salary=40*hourlyRate+(workHours-40)*hourlyRate/2

4.21 (Findthe Largest Number) The process of finding the largest value is used frequently incomputer applications. For example, a program that determines the winner of asales contest would input the number of units sold by each salesperson. Thesalesperson who sells the most units wins the contest. Write a pseudocodeprogram, then a Java application that inputs a series of 10 integers anddetermines and prints the largest integer. Your program should use at least thefollowing three variables:

a) counter: A counterto count to 10 (i.e., to keep track of how many numbers have been input and todetermine when all 10 numbers have been processed).

b) number: The integermost recently input by the user.

c) largest: The largestnumber found so far.

4.22 (TabularOutput) Write a Java application that uses looping to print thefollowing table of values:

N 10*N 100*N 1000*N

1 10 100 1000

2 20 200 2000

3 30 300 3000

4 40 400 4000

5 50 500 5000

4.23 (Findthe Two Largest Numbers) Using an approach similarto that for Exercise 4.21, find the two largestvalues of the 10 values entered. [Note: You may inputeach number only once.]

4.24 (ValidatingUser Input) Modify the program in Fig. 4.12 to validate its inputs. For anyinput,

if the value entered isother than 1 or 2, keep looping until the user enters a correct value.

4.25 What does thefollowing program print?

4.26 What does thefollowing program print?

1 //Exercise 4.25: Mystery2.java

2 publicclass Mystery2

3 {

4 publicstatic void main(String[] args)

5 {

6 int count = 1;

78

while (count<= 10)

9 {

10 System.out.println(count% 2 == 1 ? "****" : "++++++++");

11 ++count;

12 }

13 }

14 } // endclass Mystery2

1 //Exercise 4.26: Mystery3.java

2 publicclass Mystery3

3 {

4 publicstatic void main(String[] args)

5 {

6 int row = 10;

78

while (row >=1)

9 {

10 int column = 1;

11

12 while (column<= 10)

13 {

14 System.out.print(row% 2 == 1 ? "<" : ">");

15 ++column;

16 }

17

18 --row;

19 System.out.println();

20 }

21 }

22 } // endclass Mystery3

4.27 (Dangling-elseProblem) Determine the output for each of the given sets of code when x is 9 and y is 11 and when x is 11 and y is 9. Thecompiler ignores the indentation in a Java program.Also, theJava compiler always associates an else with theimmediately preceding if unless told todo otherwise by theplacement of braces ({}). On first glance, you may not be sure which if a particular else matches—thissituation is referred to as the “dangling-else problem.”We’ve eliminatedthe indentation from the following code to make the problem morechallenging. [Hint: Applythe indentation conventions you’ve learned.]

a) if (x < 10)

if (y > 10)

System.out.println("*****");

else

System.out.println("#####");

System.out.println("$$$$$");

b) if (x < 10)

{

if (y > 10)

System.out.println("*****");

}

else

{

System.out.println("#####");

System.out.println("$$$$$");

}

4.28 (AnotherDangling-else Problem) Modify thegiven code to produce the output shown in each part of the problem. Use properindentation techniques. Make no changes other than inserting braces andchanging the indentation of the code. The compiler ignores indentation in aJava program.

We’ve eliminated theindentation from the given code to make the problem more challenging.

[Note: It’s possiblethat no modification is necessary for some of the parts.]

if (y == 8)

if (x == 5)

System.out.println("@@@@@");

else

System.out.println("#####");

System.out.println("$$$$$");

System.out.println("&&&&&");

a) Assuming that x = 5 and y = 8, thefollowing output is produced:

@@@@@

$$$$$

&&&&&

b) Assuming that x = 5 and y = 8, thefollowing output is produced:

@@@@@

c) Assuming that x = 5 and y = 8, the followingoutput is produced:

@@@@@

d) Assuming that x = 5 and y = 7, thefollowing output is produced. [Note: The lastthree output statements after the else are all partof a block.]

#####

$$$$$

&&&&&

4.29 (Squareof Asterisks) Write an application that prompts the user to enter the size ofthe side of a square, then displays a hollow square of that size made of asterisks.Your program should work for squares of all side lengths between 1 and 20.

* * * * * * * *

* * * * * * * *

* * * * * * * *

* * * * * * * *

* * * * * * * *

* * * * * * * *

* * * * * * * *

* * * * * * * *

4.30 (Palindromes)A palindrome is a sequence of characters that reads the samebackward as forward.

For example, each of thefollowing five-digit integers is a palindrome: 12321, 55555, 45554 and 11611.Write an application that reads in a five-digit integer and determines whetherit’s a palindrome.

If the number is not fivedigits long, display an error message and allow the user to enter a new value.

4.31 (Printingthe Decimal Equivalent of a Binary Number) Write anapplication that inputs an integer containing only 0s and 1s (i.e., a binaryinteger) and prints its decimal equivalent. [Hint: Use theremainder and division operators to pick off the binary number’s digits one ata time, from right to left. In the decimal number system, the rightmost digithas a positional value of 1 and the next digit to the left a positional valueof 10, then 100, then 1000, and so on. The decimal number 234 can beinterpreted as 4 * 1 + 3 * 10 + 2 * 100. In the binary number system, therightmost digit has a positional value of 1, the next digit to the left apositional value of 2, then 4, then 8, and so on.

The decimal equivalent ofbinary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8, or 1 + 0 + 4 + 8 or, 13.]

4.32 (CheckerboardPattern of Asterisks) Write an application that uses only the output statements

System.out.print("*");

System.out.print("");

System.out.println();

to display thecheckerboard pattern that follows. A System.out.println method callwith no arguments causes the program to output a single newline character. [Hint: Repetitionstatements are required.]

4.33 (Multiplesof 2 with an Infinite Loop) Write an application thatkeeps displaying in the command window the multiples of the integer 2—namely,2, 4, 8, 16, 32, 64, and so on. Your loop should not terminate (i.e., it shouldcreate an infinite loop). What happens when you run this program?

4.34 (What’sWrong with This Code?) What is wrong with the following statement? Provide the correctstatement to add one to the sum of x and y.

System.out.println(++(x+ y));

4.35 (Sidesof a Triangle) Write an application that reads three nonzero values entered bythe user and determines and prints whether they could represent the sides of atriangle.

4.36 (Sidesof a Right Triangle) Write an application that reads three nonzero integers anddetermines and prints whether they could represent the sides of a righttriangle.

4.37 (Factorial)The factorial of a nonnegative integer n is written asn! (pronounced “n factorial”) andis defined as follows:

n! = n · (