package welcome; import java.util.Scanner;
/*
* 一个循环程序的设计范例
* 首先编写仅执行一次的程序(当无循环时)
* 循环的设计步骤:
* 1.确定程序中要重复执行的部分;
* 2.加上循环模板 while(true){语句块;}
* 3.重写循环控制条件,增加循环控制语句
*/ public class SubtrationQuizLoop {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5;
int correctCount = 0;
String output = "";
long startTime = System.currentTimeMillis();
Scanner in = new Scanner(System.in); int count = 0;
while(count < NUMBER_OF_QUESTIONS){ // 重写循环控制条件,增加循环控制语句
int number1 = (int) (Math.random() * 10);
int number2 = (int) (Math.random() * 10); if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
} System.out.print(" What is " + number1 + " - " + number2 + " ? ");
int answer = in.nextInt(); if (number1 - number2 == answer) {
System.out.println("You are correct!");
correctCount++;
} else {
System.out.println(
"Your answer is wrong.\n" + number1 + " - " + number2 + " should be " + (number1 - number2));
}
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer + ((number1 - number2 == answer)? " correct" : " wrong");
}
long endTime = System.currentTimeMillis();
long testTime = endTime - startTime;
System.out.println("Correct count is " + correctCount + "\nTest time is " + testTime / 1000 + " seconds\n" + output);
}
}
运行效果:
设计过程截图:
无循环的程序版本(截图):
运行示例:
循环程序设计第二步,加循环模板
第三步,重写循环继续条件,增加循环控制语句
--END--