Reputation: 73
How can I take space separated input from user in java.
abc azs ads afd atr
45 55 65
87 76 54
76 54 23
98 76 45
32 55 76
1 2 3 4 5
I tried this way but it throws error
Exception in thread "main" java.lang.NumberFormatException: For input string: "azs" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
Scanner sc = new Scanner(System.in);
String inputName = sc.next();
String[] nameArray = inputName.split(" ");
String m1 = sc.next();
String inputMarks1[]= m1.split(" ");
String m2 = sc.next();
String inputMarks2[]= m2.split(" ");
String m3 = sc.next();
String inputMarks3[]= m3.split(" ");
String m4 = sc.next();
String inputMarks4[]= m4.split(" ");
String m5 = sc.next();
String inputMarks5[]= m5.split(" ");
int marks1[] = new int[3];
int marks2[] = new int[3];
int marks3[] = new int[3];
int marks4[] = new int[3];
int marks5[] = new int[3];
for(int i =0 ; i<3;i++){
marks1[i] = Integer.parseInt(inputMarks1[i]);
marks2[i] = Integer.parseInt(inputMarks2[i]);
marks3[i] = Integer.parseInt(inputMarks3[i]);
marks4[i] = Integer.parseInt(inputMarks4[i]);
marks5[i] = Integer.parseInt(inputMarks5[i]);
}
String c = sc.next();
String classU[]= c.split(" ");
int classArray[] = new int[5];
for (int i = 0 ; i<5 ; i++){
classArray[i] = Integer.parseInt(classU[i]);
}
Upvotes: 0
Views: 56
Reputation: 31
I can think of 2 approach to modify the code:
Upvotes: 1
Reputation: 364
As far as I know, a NumberFormatException can be thrown if yourString
in Integer.parseInt(String yourString)
isn't an integral number.
Maybe that is the reason (please correct me if I am wrong).
Upvotes: 0
Reputation: 54148
The Scanner.next
method
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
And the default delimiter is space
, so each sc.next()
reads a word, not a line.
Use nextLine()
instead
Upvotes: 0