问题
I am new to java and I am still getting used to most of the syntax. Here I tried to get two inputs (the first one being an int and the second one a string) and later one I do some calculations with them. But when I run the program, it gives this message:
Exception in thread "main" java.lan._NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NuthberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Main.main(Main.java:13)
.
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
int N = myObj.nextInt();
String Input = myObj.nextLine();
String[] Inputs = Input.split(" ", 0);
int size = Inputs.length;
int [] a = new int [size];
for(int i=0; i<size; i++) {
a[i] = Integer.parseInt(Inputs[i]);
}
}
}
My understanding is that the program is assuming both inputs as the same. But how do I fix that?
回答1:
You should address the following problems with your code:
- Though not essential from the execution point-of-view, you should always display a message for the input (an example is given below); otherwise, the user remains clueless.
System.out.println("Enter a few integers separated by a space: ");
String Input = myObj.nextLine();
- Though not essential from the execution point-of-view, you should always follow Java naming conventions e.g.
int Nshould be written asint nandString[] Inputsshould beString[] inputsas per the naming conventions. - Since you are not doing anything with
N, remove the line,int N = myObj.nextInt();. - Even if you remove the line,
int N = myObj.nextInt();, you may faceNumberFormatExceptionfor inputs like10 20 30where there are more than one spaces. You should split on"\\s+"instead of" "which takes into account only one space. Note that"\\s+"will take care of one or more spaces. - Finally, even though you split on
"\\s+", you may faceNumberFormatExceptionfor inputs like10 x 30which has a non-integer entry e.g.xwhich can not be parsed into an integer. To deal with such cases, you need to handleNumberFormatExceptionas given below:
// ...
for (int i = 0; i < size; i++) {
try {
a[i] = Integer.parseInt(Inputs[i]);
// ...
} catch (NumberFormatException e) {
System.out.println("Ignoring " + Inputs[i] + " as it is not an integer.");
a[i] = Integer.MIN_VALUE;
}
// ...
}
// ...
Note that a[i] = Integer.MIN_VALUE; sets Integer.MIN_VALUE into the array for the invalid entries. You can put some other value of simply ignore it as per your requirement. If you ignore it, that index will have the default value of int which is 0.
Feel free to comment in case of any doubt/issue.
来源:https://stackoverflow.com/questions/61156113/problems-with-user-inputs-in-java