javainputmismatchexception

Java InputMismatchException is thrown for certain input in my program idk why its being thrown


Code:

import java.util.*;
public class InputInJava {
    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);


        String name = sc.next();

        String fName = sc.nextLine();

        int number =  sc.nextInt();

        float Fnumber = sc.nextFloat();

        double Dnumber = sc.nextDouble();

        short Snumber = sc.nextShort();

        byte Bnumber = sc.nextByte();

        long Lnumber = sc.nextLong();


        System.out.println(name);
        System.out.println(fName);
        System.out.println(number);
        System.out.println(Fnumber);
        System.out.println(Dnumber);
        System.out.println(Snumber);
        System.out.println(Bnumber);
        System.out.println(Lnumber);


    }
}

Input:

String String 1 1
1

i checked on overflow and a few other sites which poped up on google i tried different input such as Input2:

String String 1
1
1
1
1
1
1

Output is:

String
 String 1
1
1.0
1.0
1
1
1

So why is it reading the input for nextLine upto 1 spaces only and then it reads next input?


Solution

  • The issue you're facing is related to how the Scanner class in Java works. When you use sc.next(), it reads only one token (a sequence of characters separated by whitespace) from the input. On the other hand, when you use sc.nextLine(), it reads the entire line including any spaces until the end of the line.

    In your example, when you input "String String 1 1 1", the sc.next() reads "String", and then sc.nextLine() reads the rest of the line, which is " String 1 1 1". This is why you see unexpected behavior when trying to read the next input.

    One way to do that would be like so :

    String name = sc.next();
    // Consume the newline character left in the buffer
    sc.nextLine();