import java.util.Scanner;
public class Code_Practice_5 {
public static void main(String[] args) {
// 5.1
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer, the input ends if it is 0:");
int number = input.nextInt();
int countP = 0, countN = 0;
int total = 0, count = 0;
if (number != 0) {
// 如果写成while(true),会出现Unreachable code的问题,原因没找到
while (number != 0) {
if (number > 0)
countP++;
else
countN++;
total += number;
number = input.nextInt();
}
double average = total / (countP + countN);
System.out.println("The number of positives is " + countP);
System.out.println("The number of negatives is " + countN);
System.out.println("The total is " + total);
System.out.println("The average is " + average);
}
else
System.out.println("No numbers are entered except 0");
// 5.2
final int NUMBER_OF_QUESTIONS = 5; // Number of questions
int correctCount = 0 ; // Count the correct
int count = 0; // Count the questions
long startTime = System.currentTimeMillis();
String output = " "; // output string is initially empty;
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
// Generate two random single-digit integers
int num1 = (int)(1 + Math.random() * 14);
int num2 = (int)(1 + Math.random() * 14);
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 ++;
output += "\n" + num1 + "+" + num2 + "=" + answer +
((num1 + num2 == answer) ? " correct" : " wrong");
}
long endTime = System.currentTimeMillis();
long testTime = endTime - startTime;
System.out.println("\nCorrect count is " + correctCount +
"\nTest time is " + testTime / 1000 + " seconds\n" + output);
// 5.3
int kilo = 1;
double pound = 0;
System.out.println("千克" + " " + " 磅");
for (int i = 0; i < 199; i++) {
System.out.print(kilo);
pound = kilo * 2.2;
System.out.printf("%12.1f\n", pound);
kilo++;
}
// 5.4
int miles = 1;
double kilo = 0;
System.out.println("英里" + "
Java语言程序设计(基础篇)原书第十版 课后习题 第五章
最新推荐文章于 2020-11-23 02:04:18 发布