-1 java string if-statement java.util.scanner
在我的程序的一部分中,我放置了一个 while 循环来重复请求输入。有一个选项可以输入字母“F”并中断循环。这是我的程序:
public class Example {
public static void main(String[] args) {
int x = 0;
ArrayList Numbers = new ArrayList();
while (x==0) {
System.out.println("Type your number:");
Scanner s = new Scanner(System.in);
if (s.equals("f") || s.equals("F")) {
x = 1;
}
else if (!s.equals("f") && !s.equals("F")) {
int n = Integer.parseInt(s.next());
Numbers.add(n);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行该程序时,我输入一些数字,然后输入“F”。我看到这个错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "F"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Example.main(Example.java:13)
Run Code Online (Sandbox Code Playgroud)
我相信字符串“F”可以通过我的else if但我不知道为什么。我该如何解决这个问题?
您正在将字符串与 Scanner 对象进行比较。让我们看看扫描仪对象在 java 中是如何工作的。
Scanner myObj = new Scanner(System.in);
String myInput = myObj.nextLine(); // Read user input
Run Code Online (Sandbox Code Playgroud)
然后你可以将你的myInput字符与“f”或“F”进行比较