[JAVA] pitfalls of nextInt () → nextLine ()

I would like to pass two parameters, a number and a string, as standard input.

The method to use is nextLine (): Method that can get the input for one line up to the line feed nextInt (): Method that can get int type number There are two types, The order matters.

If nextLine () comes first, it will accept the input twice.


import java.util.*;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        String numStr = sc.nextLine();
        int num = sc.nextInt();

        sc.close();

        System.out.println(num);
        System.out.println(numStr);
    }
}

If nextLine () is later, the input will only be accepted once. numStr contains an empty string.


import java.util.*;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int num = sc.nextInt();
        String numStr = sc.nextLine();

        sc.close();

        System.out.println(num);
        System.out.println(numStr);
    }
}

This is because the newline character remains when reading a numerical value with nextInt. int+enter(\n) The remaining newline character has been read by nextLine.

As a solution other than changing the order, int num = sc.nextInt(); sc.nextLine (); ← Read line breaks here. (No need to store in variable) String numStr = sc.nextLine();

there is.

Recommended Posts

pitfalls of nextInt () → nextLine ()
[Spring] Pitfalls of BeanUtils.copyProperties
Subtle pitfalls of lombok
Pitfalls of Active Hash
Pitfalls of WebTarget.queryParam () in JAX-RS