飞道的博客

第五章第二题(重复加法)(Repeat additions)

168人阅读  评论(0)

5.2(重复加法)程序清单5-4产生了5个随机减法问题。改写该程序,使它产生10个随机加法问题,加数是两个1到15之间的整数。显示正确答案的个数和完全测试的时间。

5.2(Repeat multiplications) Listing 5.4, SubtractionQuizLoop.java, generates five randomsubtraction questions. Revise the program to generate ten random addition questions for two integers between 1 and 15. Display the correct count and test time.

下面是参考答案代码:

import java.util.*;


public class RepeatAdditionsQuestion2 {
	public static void main(String[] args){
		final int NUMBER_OF_QUESTIONS = 10; // Number of questions
	    int correctCount = 0; // Count the number of correct answers
	    int count = 0; // Count the number of questions
	    long startTime = System.currentTimeMillis();
	    String output = " "; // output string is initially empty
	    Scanner input = new Scanner(System.in);

	    while (count < NUMBER_OF_QUESTIONS) {
	        // 1. Generate two random single-digit integers
	        int number1 = (int) (1 + Math.random() * 15);
	        int number2 = (int) (1 + Math.random() * 15);

	        // 2. Prompt the student to answer "What is number1 + number2?"
	        System.out.print("What is " + number1 + " + " + number2 + "? ");
	        int answer = input.nextInt();

	        // 3. Grade the answer and display the result
	        if (number1 + number2 == answer) {
	            System.out.println("You are correct!");
	            correctCount++; // Increase the correct answer count
	        } else
	            System.out.println("Your answer is wrong.\n" + number1 + " + " 
	                                + number2 + " should be " + (number1 + number2));
	        // Increase the question count
	        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);
	    
	    input.close();
	}
}

运行效果:

注:编写程序要养成良好习惯
1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)
5.普通变量,方法名要小驼峰,类名要大驼峰,常量要使用全部大写加上下划线命名法
6.要学习相应的代码编辑器的一些常用快捷键,如:快速对齐等等


转载:https://blog.csdn.net/xjlovewjh/article/details/104312250
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场