stanford编程方法——习题答案(the art and science of java)——chapter04

  Chapter 04 Statement Forms
Review questions
-------------------------------------------------------------------------------
1. Is the construction
    17;
a legal statement in Java? Is it useful?
Answer:
    legal statement but not userful
-------------------------------------------------------------------------------
2. Describe the effect of the following statement, assuming that i, j, and k
are declared as integer variables:
    i = (j = 4) * (k = 16);
Answer:
    i = j * k
      = 4 * 16
      = 64;
-------------------------------------------------------------------------------
3. What single statement would you write to set both x and y (which you may
assume are declared to be type double) to 1.0?
Answer:
    x = y = 1.0;
-------------------------------------------------------------------------------
4. What is a block? What important fact about blocks is conveyed by the term
compound statement, which is another name for the same concept?
Answer:
    {
        statements
    }
-------------------------------------------------------------------------------
5. What are the two classes of control statements?
Answer:
    conditionals
    Iteration
-------------------------------------------------------------------------------
6. What does it mean to say that two control statements are nested?
Answer:
    a control statement is used within the body of another control statement
-------------------------------------------------------------------------------
7. What are the two values of the data type boolean?
Answer:
    true
    false
-------------------------------------------------------------------------------
8. What happens when a programmer tries to use the mathematical symbol for equality in a conditional expression?
Answer:
    assignment
-------------------------------------------------------------------------------
9. What restriction does Java place on the types of values that can be compared using the relational operators?
Answer:
    The relational operators can only be used to comapre automic data value
-------------------------------------------------------------------------------
10. How would you write a Boolean expression to test whether the value of the integer variable n was in the range 0 to 9, inclusive?
Answer:
    0 <= n && n <= 9
-------------------------------------------------------------------------------
11. Describe in English what the following conditional expression means:
    (x != 4) || (x != 17)
For what values of x is this condition true?
Answer:
    expression is always true for any x
-------------------------------------------------------------------------------
12. What does the term short-circuit evaluation mean?
Answer:
    the evaluation stops as soon as the program can determine the result   
-------------------------------------------------------------------------------
13. Assuming that myFlag is declared as a Boolean variable, what is the problem with writing the following if statement?
if (myFlag == true) . . .
Answer:
    if (myFlag) ...
-------------------------------------------------------------------------------
14. What are the four different formats of the if statement used in this text?
Answer:
(1) Single-line if statements
    if (condition) statement;
(2) Multiline if statements
    if (condition) {
        statements;
    }
(3) The if-else statement
    if (condition) {
        statementT
    } else {
        statementF
    }
(4) Cascading if statements
    if (condition1) {
        statement1
    } else if (condition2) {
        statement2
    } else if (condition3) {
        statement3
        . . .
    } else {
        statement_none
    }
-------------------------------------------------------------------------------
15. Describe in English the general operation of the switch statement.
Answer:
    switch (e) {
        case c1:
            statements1
            break;
        case c2:
            statements2
            break;
        . . . more case clauses . . .
        default:
            statements_def
            break;
    }
-------------------------------------------------------------------------------
16. Suppose the body of a while loop contains a statement that, when executed, causes the condition for that while loop to become false. Does the loop terminate immediately at that point or does it complete the current cycle?
Answer:
    complete the current cycle
-------------------------------------------------------------------------------
17. Why is it important for the DigitSum program in Figure 4-6 to specify that the integer is positive?
Answer:
    to make sure that the program will exit normally
-------------------------------------------------------------------------------
18. What is the loop-and-a-half problem? What two strategies are presented in the text for solving it?
Answer:
    a loop contians some operations thata must be perfromed before testing
for completion
(1) read-until-sentinel  pattern
    while (true) {
        prompt user and read in a value
        if (value == sentinel) break;
        rest of body
    }
(2) value != sentinel
    prompt user and read in a value
    while (value != sentinel) {
        process the data value
        prompt user and read in a new value
    }
-------------------------------------------------------------------------------
19. What is the purpose of each of the three expressions that appear in the control line of a for statement?
Answer:
    for (init; test; step) {
        statements
    }   
-------------------------------------------------------------------------------
20. What for loop control line would you use in each of the following situations:
a) Counting from 1 to 100.
b) Counting by sevens starting at 0 until the number has more than two digits.
c) Counting backward by twos from 100 to 0.
Answer:
a) Counting from 1 to 100.
    for (int i = 1; i <= 100; i++) {
        ...
    }
b) Counting by sevens starting at 0 until the number has more than two digits.
    for ( int i = 0; i < 100; i += 7) {
        ...
    }
c) Counting backward by twos from 100 to 0.
    for (int i = 100; i >= 0; i--) {
        ...
    }
-------------------------------------------------------------------------------
21. Why is it best to avoid using a floating-point variable as the index variable in a for loop?
Answer:
    because floating-point numbers are only approximations
-------------------------------------------------------------------------------
Programming exercises
1. As a way to pass the time on long bus trips, young people growing up in the United

States have been known to sing the following rather repetitive song:
99 bottles of beer on the wall.
99 bottles of beer.
You take one down, pass it around.
98 bottles of beer on the wall.
98 bottles of beer on the wall. . . .

Anyway, you get the idea. Write a Java program to generate the lyrics to this song.
(Since you probably never actually finished singing it, you should decide how you
want the song to end.) In testing your program, it would make sense to use some
constant other than 99 as the initial number of bottles.

/*
 * File: BottlesOfBeer.java
 * -------------------------
 * This program generates the lyrics to the 99 Bottles of Beer.
 */
import acm.program.*;
public class BottlesOfBeer extends ConsoleProgram {
	public void run() {
		int end = readInt("Please input an integer between 0 and " + TOTAL_BOTTLES_OF_BEER + ": ");
		while (end < 0 || end >= TOTAL_BOTTLES_OF_BEER) {
			println(end + " isn't between 0 and " + TOTAL_BOTTLES_OF_BEER + 
					"( x < 0 or  x >= "+TOTAL_BOTTLES_OF_BEER + ").");
			end = readInt("Please input an integer between 0 and " + TOTAL_BOTTLES_OF_BEER+ ": ");
		}
		int i = TOTAL_BOTTLES_OF_BEER;
		while (i != end) {
			if (i != 0 ){
				println(i + " bottles of beer on the wall, " + i + " bottles of beer.");
				println("Take one down and pass it around, " + --i + " bottles of beer on the wall.");

			} else {
				println("No more bottles of beer on the wall, no more bottles of beer." );
				println("Go to the store and buy some more, 99 bottles of beer on the wall.");
			}
		}
		
	}
	private static final int TOTAL_BOTTLES_OF_BEER = 99;
}

2. While we’re on the subject of silly songs, another old standby is “This Old Man,” for
which the first verse is
This old man, he played 1.
He played knick-knack on my thumb.
With a knick-knack, paddy-whack,
Give your dog a bone.
This old man came rolling home.
Each subsequent verse is the same, except for the number and the rhyming word at
the end of the second line, which gets replaced as follows:
2—shoe 5—hive 8—pate
3—knee 6—sticks 9—spine
4—door 7—up to heaven 10—shin
Write a program to display all 10 verses of this song.

/*
 * File: ThisOldMan.java
 * ---------------------
 * This program generates the silly songs named by "This Old Man".
 */
import acm.program.*;

public class ThisOldMan extends ConsoleProgram {
	private static final String array[] = {"thumb", "shoe", "knee", "door",
			"hive", "sticks", "up to heaven", "pate", "spine", "shin"};
	private static final String  num_arr[] = {"one", "two", "trhee", "four",
			"five", "six", "seven", "eight", "nine", "ten"};
	public void run() {
		for (int i = 0; i < 10; i++) {
			println("This old man, he played " + num_arr[i] + ".");
			println("He played knick-knack on my "
					 + array[i] + ".");
			println("With a knick-knack, paddy-whack,");
			println("Give your dog a bone.");
			println("This old man came rolling home");
			println("");
		}
	}
}

3. Write a program that reads in a positive integer N and then calculates and displays
the sum of the first N odd integers. For example, if N is 4, your program should
display the value 16, which is 1 + 3 + 5 + 7.

/*
 * File: SumOfTheFirstNOddIntergers.java
 * -------------------------------------
 * This program taht reads  in a positive intteger N and then calculates
 * and displays the sum of the first N odd intergers. For example, if N
 * is 4, your program should display the value 16, which is 1 + 3 + 5 +7.
 */
import acm.program.*;

public class SumOfTheFirstNOddIntergers extends ConsoleProgram {
	public void run () {
		int sum = 0;
		int N = readInt("Please Enter a positive integer N: ");
		while (N <= 0) {
			N = readInt("Please Enter a positive integer N: ");
		}
		for (int i = 0, odd = 1; i < N; i++, odd += 2 )
			sum += odd;
		println("the sum of the first " + N 
			+ " odd intergers is " + sum + ".");
	}
}

4. Why is everything either at sixes or at sevens?
— Gilbert and Sullivan, H.M.S. Pinafore, 1878
Write a program that displays the integers between 1 and 100 that are divisible by
either 6 or 7.

/*
 * File: DisplayIntegersDividedBy6or7Between1And100.java
 * -----------------------------------------------------
 * This program displays the integers between 1 and 100 that are 
 * divisible by either 6 or 7.
 */
import acm.program.*;

public class DisplayIntegersDividedBy6or7Between1And100 extends ConsoleProgram {
	public void run() {
		for (int i = 1; i <= 100; i++) {
			if ((i % 6 == 0) || (i % 7 == 0)) {
				println(i + " is divived by either 6 or 7.");
			}
		}
	}
}

5. Repeat exercise 4, but this time have your program display only those numbers that
are divisible by 6 or 7 but not both.

DisplayIntegersDividedBy6Xor7Between1And100.java

6. Using the AddIntegerList program from Figure 4-5 as a model, write a program
called AverageList that reads in a list of integers representing exam scores and then
prints out the average. Because some unfortunate student might actually get a score
of 0, your program should use –1 as the sentinel to mark the end of the input.

AverageList.java

7. Rewrite the DigitSum program given in Figure 4-6 so that instead of adding the
digits in the number, it generates the number that has the same digits in the reverse
order, as illustrated by this sample run:

/*
 * File: ReverseDigits.java
 * ----------------------------------
 * This program reverses the digits in an integer.
 */
import acm.program.*;

public class ReverseDigits extends ConsoleProgram {
	public void run() {
		println("This program reverses the digits in an integer.");
		int num = readInt("Enter a positive integer: ");
		while (num <= 0) {
			num = readInt("Enter a positive integer: ");
		}
		int rev = 0;
		while (num > 0) {
			rev *= BASE;
			rev += num % 10;
			num /= 10;
		}
		println("The reversed num is: " + rev);
	}
	private static final int BASE = 10;
}

8. Rewrite the Countdown program given in Figure 4-8 so that it uses a while loop
instead of a for loop.

/*
 * File: CountDownUsingWhile.java
 * --------------------
 * This program counts backwards from the value START
 * to zero, as in the countdown preceding a rocket
 * launch.
 */
import acm.program.*;
public class CountDownUsingWhile extends ConsoleProgram {
	/* Specifies the value from which to start counting down */
	private static final int START = 10;
	/* Runs the program */
	public void run() {
		int t = START;
		while (t >= 0) {
			println("Liftoff!");
			t--;
		}
	}
}

9. In mathematics, there is a famous sequence of numbers called the Fibonacci
sequence after the thirteenth-century Italian mathematician Leonardo Fibonacci. The
first two terms in this sequence are 0 and 1, and every subsequent term is the sum of
the preceding two. Thus the first several numbers in the Fibonacci sequence are as
follows:
F0 = 0
F1 = 1
F2 = 1 (0 + 1)
F3 = 2 (1 + 1)
F4 = 3 (1 + 2)
F5 = 5 (2 + 3)
F6 = 8 (3 + 5)
Write a program to display the values in this sequence from F0 through F15.

/*
 * File: FibonacciSequencesFromF0ThroughF15.java
 * ---------------------------------------------
 * This program displays the value of Fibonacci sequence from F0
 * through F15.
 */
import acm.program.*;

public class FibonacciSequencesFromF0ThroughF15 extends ConsoleProgram {
	public void run() {
		int [] array = new int[16];
		
		array[0] = 0;
		array[1] = 1;
		for (int i = 2; i <= 15; i++)
			array[i] = array[i-1] + array[i-2];
		for (int i = 0; i <= 15; i++) {
			println("F" + i + " = " + array[i]);
		}
	}
}

10. Modify the program in the preceding exercise so that instead of specifying the index
of the final term, the program displays those terms in the Fibonacci sequence that are
less than 10,000.

/*
 * File: FibonacciSeqenceLessThan1000.java
 * This program dispplays those terms in the Fibonacci
 * sequence that less than 1000
 */

import acm.program.*;
import java.math.*;

public class FibonacciSeqenceLessThan1000 extends ConsoleProgram {
	private static final  int LAST_INDEX = 1000;
	public void run() {
		BigInteger[] array =  new BigInteger[LAST_INDEX];
		
		array[0] = new BigInteger("0");
		array[1] = new BigInteger("1");
		for (int i = 2; i < LAST_INDEX; i++) {
			array[i] = new BigInteger(array[i - 2].add(array[i - 1]).toString());
		}
		for (int i = 0; i < LAST_INDEX; i++) {
			println("F" + i + " = " +  array[i]);
		}
	}
	
}

11. Write a GraphicsProgram that uses two nested for loops to create the following
checkerboard diagram in the upper left corner of the canvas:

The individual squares are all instances of the class GRect introduced in Chapter 2.
Alternate squares both horizontally and vertically contain a somewhat smaller GOval
to create the checkerboard effect.

/*
 * File: Checkerboard.java
 * -----------------------
 * This program draws a checkerboard.
 */
import acm.graphics.*;
import acm.program.*;
/*
 * This class draws a checkerboard on the graphics window.
 * The size of the checkerboard is specified by the
 * constants NROWS and NCOLUMNS, and the checkboard fills
 * the vertical space available.
 */
public class Checkerboard extends GraphicsProgram {
	/* Number of rows */
	private static final int NROWS = 8;
	/* Number of columns */
	private static final int NCOLUMNS = 8;
	/* Runs the program */
	public void run() {
		int sqSize = getHeight() / NROWS;
		for (int i = 0; i < NROWS; i++) {
			for (int j = 0; j < NCOLUMNS; j++) {
				int x = j * sqSize;
				int y = i * sqSize;
				GRect sq = new GRect(x, y, sqSize, sqSize);
				if ((i + j)% 2 != 0)
					 add(new GOval(x + 4, y + 4, sqSize-8 , sqSize-8));
				add(sq);
			}
		}
	}
}

12. Using much the same strategy as you did in the preceding exercise, write a
GraphicsProgram that creates a simple calendar diagram similar to the one shown in
the following diagram:

Your program should use the following named constants to control the format of the
calendar display:

/* The number of days in the month */ private static final int DAYS_IN_MONTH = 31; /* The day of the week on which the month starts */ /* (Sunday = 0, Monday = 1, Tuesday = 2, and so on) */ private static final int DAY_MONTH_STARTS = 5; /* The width in pixels of a day on the calendar */ private static final int DAY_WIDTH = 40; /* The height in pixels of a day on the calendar */ private static final int DAY_HEIGHT = 30;

Your display should generate exactly the number of rows necessary to display the
days of the month. Here, in a 31-day month that begins on a Friday, the calendar
needs six rows; if you were generating a calendar for a non-leap-year February that
began on a Sunday, the calendar would require only four rows.

/*
 * File: Calendar.java
 * -------------------
 * This program displays a simple calendar diagram.
 */
import acm.graphics.*;
import acm.program.*;

public class Calendar extends GraphicsProgram {
	/* The number of days in the month */
	private static final int DAYS_IN_MONTH	= 31;

	/* The day of the week on which the month starts */
	/* (Sunday = 0, Monday = 1, Tuesday = 2, and so on) */
	private static final int DAY_MONTH_STARTS = 5;
	/* the width in pixels of a day on the calendar */
	private static final int  DAY_WIDTH = 40;
	/* the number of rows */
	private static final int NROWS = (DAYS_IN_MONTH + DAY_MONTH_STARTS) / 7 
			+ ((DAYS_IN_MONTH +DAY_MONTH_STARTS) % 7 == 0 ? 0 : 1);
	private static final int NCOLUMNS = 7;
	public void run() {
		for (int i = 0; i < NROWS; i++) {
			for (int j = 0; j < NCOLUMNS; j++) {
				int x = j * DAY_WIDTH;
				int y = i * DAY_WIDTH;
				GRect sq = new GRect(x, y, DAY_WIDTH, DAY_WIDTH);
				x = j * DAY_WIDTH;
				y = i * DAY_WIDTH;
				if ((i * 7 + j) >= DAY_MONTH_STARTS && (i * 7 + j - DAY_MONTH_STARTS) < DAYS_IN_MONTH)
					add(new GLabel((i*7+j - DAY_MONTH_STARTS + 1) + ""), x + 4, y + 14);
				add(sq);
			}
		}
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值