-2

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?

2
  • #nextLine will read up to the newline character (including spaces and numbers). #next will read up to a delimiter (which excludes whitespace from being read). Your current code necessitates that the six expected numbers come after the newline. Commented Jan 2, 2024 at 16:15
  • For future reference, questions of this type should include a copy of the stack trace. It also helps if the question indicates which line in your source code caused the exception to be thrown. Use text copy-and-paste to ensure accuracy. Commented Jan 2, 2024 at 16:26

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.