Java using multiple scanners

I have this problem a lot. When I use the scanner many times, it does not receive input from the user.

Scanner scan = new Scanner(System.in);

        System.out.println("1---");

        int try1 = scan.nextInt();

        System.out.println("2---");

        int try2 = scan.nextInt();

        System.out.println("3---");

        String try3 = scan.nextLine();

        System.out.println("4---");

        String try4 = scan.nextLine();

When I run this code, output it:

1 ---

12

2 ---

321

3 ---

4 ---

aa

As you can see, he missed the third entrance. Why is this happening? I solve this problem with new scanners, sometimes I have 5-6 different scanners, and it looks so complicated. Another problem: the error "leak of resources: the scan never closes." I'm really confused.

+4
source share
3 answers

api, nextLine, nextInt, , , +\n, nextInt \n, , , , .. try3, .

        Scanner scan = new Scanner(System.in);

    System.out.println("1---");

    int try1 = scan.nextInt();

    System.out.println("2---");

    int try2 = scan.nextInt();

    System.out.println("3---");

    String try3 = scan.next();

    System.out.println("4---");

    String try4 = scan.next();
+2

, scanner.nextInt() , , (\n), Enter.

, scanner.nextLine(), (\n) , . , input.nextLine().

 System.out.println("2---");
 int try2 = scan.nextInt();
 System.out.println("3---");
 scan.nextLine(); //<-- fake statement, to move the cursor on the next line
 String try3 = scan.nextLine();

, Scanner , :

scan.close();
+6

Ok, for the first question use

scan.next ()

via

scan.nextLine ();

In the second question, I would recommend using try, assuming you need to close the scan, as your compiler warns: "Resource leak: the scan never closes"

Scanner scanner= null;
  try {
    scanner= new Scanner(System.in);

  }
  finally {
    if(scanner!=null)
    scanner.close();
 }
0
source

All Articles