In a part of my program, I put a while loop to repeatedly ask for inputs. There is an option to type in letter "F" and break the loop. This is my program:
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);
}
}
}}
When I run the program, I type some numbers and then type "F". I see this error:
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)
I believe the String "F" can pass through my else if but I don't know why. How can I solve this?
Aucun commentaire:
Enregistrer un commentaire