Java语言程序设计基础篇第10版第5章习题答案

时间:2023-12-21 16:55:08
5.1
1 public class Demo {
public static void main(String[] args) {
// 创建一个输入对象
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter an integer,the input ends if it is 0: ");
//输入一串整数以空格隔开,如果输入0,程序结束
int num = input.nextInt();
//定义正数与负数的个数变量,定义输入值得总和(不包括0)
int positiveNum = 0, negativeNum = 0;
double sum = 0;
//判断输入的第一个整数是否为0,如果不是,继续判断,如果是,直接else
if (num != 0) {
//读入的整数计算正数个数、负数个数、总和,直到读入为0跳出循环
while (num != 0) {
if (num > 0)
positiveNum++;
else
negativeNum++;
sum += num;
num = input.nextInt();
}
//输出相应的正数、负数、总和和平均数的值
System.out.println("The number of positives is " + positiveNum);
System.out.println("The number of negatives is " + negativeNum);
System.out.println("The total is " + sum);
System.out.println("The average is " + sum
/ (positiveNum + negativeNum));
}else
System.out.println("No numbers are entered except 0");
}
}
5.2
1 public class Demo {
public static void main(String[] args) {
// 定义问题的数量为10
final int NUMBER_OF_QUESTIONS = 10;
// 定义变量存放正确的个数,定义变量存放循环次数
int correctCount = 0;
int count = 1;
// 定义开始时间
long startTime = System.currentTimeMillis();
// 创建一个输入对象
java.util.Scanner input = new java.util.Scanner(System.in);
// 随机产生两个整数,循环10次
while (count <= 10) {
// 定义两个整数变量,存放随机产生的1~15内的整数
int num1 = (int) (Math.random() * 15) + 1;
int num2 = (int) (Math.random() * 15) + 1;
// 输入答案
System.out.print("What is " + num1 + " + " + num2 + "? ");
int answer = input.nextInt();
// 如果回答正确,正确的个数加一,回答不正确,输出正确的结果
if (num1 + num2 == answer) {
System.out.println("You are correct!");
correctCount++;
} else
System.out.println("Your answer is wrong.\n" + num1 + " + "
+ num2 + " should be " + (num1 + num2));
// 循环次数加一
count++;
}
// 定义结束时间
long endTime = System.currentTimeMillis();
// 计算测验时间
long testTime = endTime - startTime;
// 输出正确答案的个数与测验时间(单位秒)
System.out.println("Correct count is " + correctCount
+ "\nTest time is " + testTime / 1000 + " seconds");
}
}