0

My input will be

12
4.0
has to be concatenated with this input

My Expected output is

16
8.0
RandomString has to be concatenated with this input

My code which tries to do this is follows

        int i = 4;
        double d = 4.0;
        String s = "RandomString";

        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt(); 
        double e = scan.nextDouble();
        String str = scan.nextLine();
        int resInt = i + j; double resDouble = d + e; String resString = s +" "+ str;
        System.out.println(resInt);
        System.out.println(resDouble);
        System.out.println(resString);

        scan.close();

This behaves differently. As soon as I enter two lines of input it is giving me output. Not waiting for third line of my input. So now my output is

12
4.0
16
8.0
RandomString

1 Answer 1

1

Primitive data types like int, double does not consume Enter key/End of line. That's why enter typed after keying integer is taken as value from buffer for your nextLine().

When you want to use the same scanner object with nextInt(), and a nextLine(), It doesn't work well.

There are two solutions to this, Solutions are to create another scanner to read string OR give an extra nextLine() before attempting to read the random string as given below.

Scanner scan = new Scanner(System.in);
int j = scan.nextInt();
double e = scan.nextDouble();
scan.nextLine();
String str = scan.nextLine();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.