Program
Program

Reputation: 73

How to read input in space format in java

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

Answers (3)

BEdits
BEdits

Reputation: 31

I can think of 2 approach to modify the code:

  1. use scanner.nextLine() instead of next. This will return the entire string. Then from the string use split(" ") function to extract string array and then parse it for int. Else
  2. use scanner.nextInt() instread of next(). This will directly take the token and will parse it and return you the int .

Upvotes: 1

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

azro
azro

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

Related Questions