我的代码编译但是一旦我运行它,它会询问用户输入然后停止。但是,程序说它仍在运行,但它不会继续执行其余代码,我无法弄清楚原因。
这是我代码的一部分。在我询问用户他们想要回答多少问题后,它就会停止。根据我的调试器,它专门停在“qNum = console.nextInt();”当我输入有效的输入时。
import java.util.*;
import java.io.*;
public class QuizBowlRedo implements Quiz {
private Player player; // player object
private String file; // name of file
private int qNum; // number of questions player wants to answer
private int qNumFile; // number of questions in file
private ArrayList<Question> questionsArr; // holds Question objects
private boolean questionsAsked[];
// Constructor
public QuizBowlRedo(String fName, String lName, String file) throws FileNotFoundException {
player = new Player(fName, lName);
Scanner gameFile = new Scanner(new File(file));
qNum = numOfQuestionsToPlay();
qNumFile = maxNumQFile(gameFile);
questionsArr = new ArrayList<Question>();
readFile();
questionsAsked = new boolean[qNumFile];
}
// asks user how many questions to ask
public int numOfQuestionsToPlay() {
Scanner console = new Scanner(System.in);
// CHECKS FOR VALID USER INPUT
boolean check = false;
do {
try {
System.out.print("How many questions would you like (out of 3)? ");
if(console.nextInt() > 3) {
System.out.println("Sorry, that is too many.");
check = false;
}
else {
check = true;
qNum = console.nextInt();
}
}
catch(InputMismatchException e) {
System.out.println("Invalid input. Please try again.");
console.nextLine();
check = false;
}
}
while(check == false);
return qNum;
}
答案 0 :(得分:1)
您在程序中的两个不同位置调用nextInt()
,因此如果您的程序进入“else”块,那么它将等待第二次结果。
您应该只调用nextInt()
一次,并在继续之前将结果分配给局部变量。你可以这样做。
System.out.print("How many questions would you like (out of 3)? ");
int answer = console.nextInt();
if(answer > 3) {
System.out.println("Sorry, that is too many.");
check = false;
}
else {
check = true;
qNum = answer;
}
答案 1 :(得分:0)
console.nextInt()
读取整数,因此除非您想读取整数,否则不得调用它。
试试这个:
System.out.print("How many questions would you like (out of 3)? ");
if((qNum = console.nextInt()) > 3) {
System.out.println("Sorry, that is too many.");
check = false;
}
else {
check = true;
}