我爲我初學Java類中的分配工作循環誤差-should是令人驚訝的簡單。該程序是一個利用嵌套while循環的數學測驗。我遇到了一個程序提前結束的問題。下面是產生問題的塊的代碼:JAVA嵌套而
它應該循環輸入的次數爲NumberOfQuestionsInteger,但是它只循環一次,無論您爲NumberOfQuestionsInteger輸入什麼內容。
該代碼是有點馬虎,因爲我一直在搞一切試圖讓它工作。
編輯:更新,以完整的代碼。
代碼工作當我禁用threeTries循環。
任何幫助將大大apreciated!
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--; } */
}
}
請把完整的代碼,實際輸出與預期輸出。 –
聲明/不顯示threeTries的初始值,這是很重要的 –
你是遞減'你內心的循環內NumberOfQuestionsInteger'。如果這個循環僅用於解答,那麼考慮將'NumberOfQuestionsInteger = NumberOfQuestionsInteger - 1;'移到外部循環。 – Pshemo