4.1在A处count < 100总是true;在C处count < 100总是false;在B处count < 100有时是true有时是false
4.2 guess被初始化为1到100之间的数都是错误的,因为这都是要猜的数。
4.3 a)和b)循环无数次;c)循环9次输出是3,5,7,9一行输出一个数。
4.4 public class test3 {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
int sum = 0;
int number;
do{
System.out.print("Enter an number: ");
number = input.nextInt();
sum += number;
}while(number != 0);
System.out.println(sum);
}
}
4.5 具有相同的值。
4.6 for(int i = 1; i <= 100; i++){
System.out.println(i);
4.7 max is 5 number 0
4.8 sum is 14 count is 5
4.9 max is 5 number 0
4.10 The loop keeps doing something indefinitely.
4.11 No. The scope of the variable is inside the loop.
4.12 Yes. The advantages of for loops are simplicity and readability. Compilers can produce more efficient code for the for loop than for the corresponding while loop.
4.13 while loop:
long sum = 0;
int i=0;
while (i<=1000) {
sum += i++;
}
do-while loop:
long sum = 0;
int i = 0;
do {
sum += i++;
}while (i <= 1000);
4.14 程序不会工作。
4.15 break跳出整个循环,continue跳出循环的当前迭代。A)能结束结果是Balance is 1,B)不能结束。
4.16 Yes. for (int i=1; sum < 10000; i++)
sum = sum + i;
4.18
class TestBreak {
public static void main(string[]args) {
int sum = 0;
int number = 0;
while (number < 20 && sum < 100) {
number++;
sum += number;
}
System.out.println("The sum is " + sum);
}
}
class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number != 10 && number != 11)
sum += number;
}
System.out.println("The sum is " + sum);
}
}
4.19 System.out.println(i);
1
2
1
2
2
3
4.20 j++
1
2
1
2
2
3