Java While循环解析问题
我试图给用户无限量的输入,直到他们输入q。我使用while语句来运行程序,但是当用户试图退出时,我得到一个错误,因为程序会尝试将q解析为整数。关于我应该如何改变这个结构以防止错误发生,有什么想法吗Java While循环解析问题,java,oop,Java,Oop,我试图给用户无限量的输入,直到他们输入q。我使用while语句来运行程序,但是当用户试图退出时,我得到一个错误,因为程序会尝试将q解析为整数。关于我应该如何改变这个结构以防止错误发生,有什么想法吗 Scanner in = new Scanner(System.in); System.out.println("What would you like your Fibonacci number to be?(enter q to quit)"); String value = in.next()
Scanner in = new Scanner(System.in);
System.out.println("What would you like your Fibonacci number to be?(enter q to quit)");
String value = in.next();
int trueValue;
while(!value.equalsIgnoreCase("q")) {
trueValue = Integer.parseInt(value);
Fibonacci userCase = new Fibonacci(trueValue);
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
System.out.println("Please enter another number.");
value = in.next();
trueValue = Integer.parseInt(value);
}
如果重要的话,这里是在循环中调用的方法
public int calculateFibonacci(int caseValue) {
if(caseValue == 0)
return 0;
else if(caseValue == 1)
return 1;
else
return calculateFibonacci(caseValue-1) + calculateFibonacci(caseValue-2);
}
public int getCaseValue()
{
return caseValue;
}
您可以删除最后一个
trueValue = Integer.parseInt(value);
因为你已经在循环的开始做了 do{检查前获取用户值}同时检查是否正常
/* https://stackoverflow.com/questions/40519580/trying-to-determine-if-a-string-is-an-integer */
private boolean isInteger(String str) {
if(str == null || str.trim().isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static String check(Scanner in) {
String value;
do {
System.out.println("Please enter a number or q to quit.");
value = in.next();
} while(!value.equalsIgnoreCase("q") && !isInteger(value));
return value;
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
String value = check(in);
while(!value.equalsIgnoreCase("q")) {
Fibonacci userCase = new Fibonacci(Integer.parseInt(value));
System.out.println(userCase.calculateFibonacci(userCase.getCaseValue()));
value = check(in);
}
in.close();
}
检查它是否为q,如果不是,则仅将其解析为整数?是否有任何原因需要在循环的开始和结束时解析整数?但如果字符串value=in.next中给出的输入也将失败;不是q也不是int。@JuanCarlosMendoza你是对的,该程序将在该场景中出错,但该行为未针对该场景定义。它应该继续吗?出错?使用最后一个数字作为有效输入并重复该过程?它说,它应该退出Q,但没有定义其他输入要考虑。