gpt4 book ai didi

Java 程序在请求用户输入后停止运行

转载 作者:行者123 更新时间:2023-12-01 10:14:44 25 4
gpt4 key购买 nike

我的代码可以编译,但一旦运行它,它就会要求用户输入,然后停止。然而,程序说它仍在运行,但它没有继续执行其余的代码,我不明白为什么。

这是我的代码的一部分。当我询问用户他们想回答多少问题后,它就会停止。根据我的调试器,它特别停在“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;
}

最佳答案

您在程序中的两个不同位置调用 nextInt(),因此如果您的程序进入“else” block ,那么它将再次等待结果。

您应该只调用 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;
}

关于Java 程序在请求用户输入后停止运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35966517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com