我正在为我的初学Java类工作。该程序是一个利用嵌套while循环的数学测验。我对程序过早结束有问题。以下是产生问题的块的代码:
它应该循环输入作为NumberOfQuestionsInteger输入的次数,但无论你为NumberOfQuestionsInteger输入什么,它都只循环一次。
代码有点草率,因为我一直在搞乱所有试图让它工作的东西。
编辑:更新为完整代码。
当我禁用threeTries循环时代码有效。
任何帮助都会有很大帮助!
import javax.swing.JOptionPane;
import java.util.Random; //import Random class
public class HroudaASSN2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String NumberOfQuestions = JOptionPane.showInputDialog("How Many Questions Would You Like To Answer?");
int NumberOfQuestionsInteger = Integer.parseInt(NumberOfQuestions); //Converts string to Integer, I named it NumberOfQuestionsInteger so as to make that clear.
int score, threeTries;
threeTries = 3;
score = 0;
while (NumberOfQuestionsInteger > 0) // Allows the program to run until exited.
{
Random firstNum1 = new Random(); //create an object of Random class
int firstNum = firstNum1.nextInt(100) + 1; //generate number between 1 and 100.
Random secondNum2 = new Random(); //create an object of Random class
int secondNum = secondNum2.nextInt(100) + 1; //generate2 number between 1 and 100.
while(threeTries > 0){
String Answer = JOptionPane.showInputDialog("Score :" + score +"\ntries remaining: " + threeTries + "\n\n\n" + firstNum + "+" + secondNum);
int AnswerInteger = Integer.parseInt(Answer); //Converts string to Integer.
if (AnswerInteger == firstNum + secondNum)
{
threeTries = 0;
JOptionPane.showMessageDialog(null," Correct! \n +5 Points!");
score = score + 5;
NumberOfQuestionsInteger = NumberOfQuestionsInteger-1;
}
else
{
threeTries = threeTries - 1;
NumberOfQuestionsInteger = NumberOfQuestionsInteger-1;
}
}
}
/* if (threeTries > 0);{
comment.equals("Please Try Again!");
}
else
{comment.equals("No Attempts Remaining!");
JOptionPane.showMessageDialog(null," Wrong! \n -1 Point! \n Please Try Again!");
score = score--; } */
}
}
答案 0 :(得分:0)
你需要:
在外循环中递减NumberOfQuestionsInteger
,所以移动
NumberOfQuestionsInteger = NumberOfQuestionsInteger - 1;
从内部循环中的if
到外循环。
重置每个内循环之前的可用尝试次数,以便移动
threeTries = 3;
在外圈开始时
您不需要很少Random
级的实例。一个就够了。也不要在循环中初始化它。在循环之前执行此操作
Random rand = new Random();
while(NumberOfQuestionsInteger > 0){
int firstNum = rand.nextInt(100) + 1;
int secondNum= rand.nextInt(100) + 1;
//...
}
答案 1 :(得分:0)
threeTries = 3;
while(threeTries > 0){
String Answer = JOptionPane.showInputDialog("Score :" + score +"\ntries remaining: " + threeTries + "\n\n\n" + firstNum + "+" + secondNum);
int AnswerInteger = Integer.parseInt(Answer); //Converts string to Integer.
if (AnswerInteger == firstNum + secondNum)
{
threeTries = 0;
JOptionPane.showMessageDialog(null," Correct! \n +5 Points!");
score = score + 5;
}
else
{
threeTries = threeTries - 1;
}
}
NumberOfQuestionsInteger = NumberOfQuestionsInteger-1;