java如何让程序在提出指定数量的问题后停止提问?
import java.util.Scanner;
public class MathPractice {
public static void main(String[] args) {
// Luke Mihalovich
Scanner keyboard = new Scanner(System.in);
int questions = getNumberOfQuestions();
int difficulty = getQuestionDifficulty();
while (questions > 0) {
int random1 = (int)(9 * Math.random()) + 1;
int random2 = (int)(9 * Math.random()) + 1;
int randomSign = (int)(4 * Math.random()) + 1;
int answerAdd;
int rightAdd;
int answerSub;
int rightSub;
int answerMul;
int rightMul;
int answerDiv;
int rightDiv;
if(randomSign == 1) {
System.out.print("Question #" + questions + " What is " + random1 + " + " + random2 + "? ");
answerAdd = keyboard.nextInt();
rightAdd = random1 + random2;
if (answerAdd == rightAdd) {
System.out.println("Correct!");
} else if (answerAdd != rightAdd) {
System.out.print("Wrong... The answer is " + rightAdd);
}
}
if(randomSign == 2) {
System.out.print("Question #" + questions + " What is " + random1 + " - " + random2 + "? ");
answerSub = keyboard.nextInt();
rightSub = random1 - random2;
if (answerSub == rightSub) {
System.out.print("Correct!");
} else if (answerSub != rightSub) {
System.out.print("Wrong... The answer is " + rightSub);
}
}
if(randomSign == 3) {
System.out.print("Question #" + questions + " What is " + random1 + " * " + random2 + "? ");
answerMul = keyboard.nextInt();
rightMul = random1 * random2;
if (answerMul == rightMul) {
System.out.print("Correct!");
} else if (answerMul != rightMul) {
System.out.print("Wrong... The answer is " + rightMul);
}
}
if(randomSign == 4) {
System.out.print("Question #" + questions + " What is " + random1 + " / " + random2 + "? ");
answerDiv = keyboard.nextInt();
rightDiv = random1 / random2;
if (answerDiv == rightDiv) {
System.out.print("Correct!");
} else if (answerDiv != rightDiv) {
System.out.print("Wrong... The answer is " + rightDiv);
}
}
questions++;
}
}
public static int getNumberOfQuestions() {
Scanner keyboard = new Scanner(System.in);
int questions = 0;
System.out.print("How many questions do you want? ");
questions = keyboard.nextInt();
while(questions < 1) {
System.out.println("The number of questions must be 1 or more.");
System.out.print("How many questions do you want? ");
questions = keyboard.nextInt();
}
return questions;
}
public static int getQuestionDifficulty() {
Scanner keyboard = new Scanner(System.in);
int difficulty = 0;
System.out.print("What difficulty level do you want (1=low or 2=high)? ");
difficulty = keyboard.nextInt();
while (difficulty > 1 | difficulty > 2) {
System.out.println("Valid levels are 1 or 2. Please reenter. ");
System.out.print("What difficulty level do you want (1=low or 2=high)? ");
difficulty = keyboard.nextInt();
}
return difficulty;
}
}
我的程序应该向用户询问他们想问的问题的数量,然后程序应该询问许多随机生成的数学问题。我需要在我的程序中修正什么,才能在达到这么多问题后停止提问?还有,我如何让我的问题从#1开始?谢谢
# 1 楼答案
您可以使用
for
循环替换
与
然后也替换代码,如
与
另外,根据您的代码注释
这是错误的,应该是错误的
编辑
我注意到您的代码中有
questions++;
,请删除它