-1

I am running this code to get 3 values: an integer, a string and a boolean from the user and print it in separate lines.

import java.util.*;

public class Practice {
  public static void main(String[] args){
    int a;
    String b;
    boolean c;

    Scanner scanner = new Scanner(System.in);

    a = scanner.nextInt();
    b = scanner.nextLine();
    c = scanner.nextBoolean();

    System.out.println(a);
    System.out.println(b);
    System.out.println(c);

   }
}

I am trying to give input like this:

1
hello world
true

and am getting this error after writing the second line of input

  • hello welcome to stackoverflow what does the error showed while you writing the second line of input? my guess is because the newline character got scan into your variable `b`, thats happened because `nextInt()` does not scan the newline character so your "enter" will be scanned to variable `b`, for more detailed answer check here https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo – Aleson Oct 11 '22 at 06:17

2 Answers2

0

next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

public static void main(String... args) {
    Scanner scan = new Scanner(System.in);

    int a = scan.nextInt();
    String b = scan.next();
    boolean c = scan.nextBoolean();

    System.out.println(a);
    System.out.println(b);
    System.out.println(c);
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

so basically you can use next() instead of nextLine() or reorder if you really need to use nextLine()

b = scanner.nextLine();
a = scanner.nextInt();
c = scanner.nextBoolean();