I often struggle with Java scanner. In this case, if I don't create a new scanner object inside the if statement, it does not allow me to enter the string. The complier shows no error but I don't understand why it behaves like that. I want to know the best practice to deal with this situation.
import java.util.Scanner;
public class testing {
public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter an integer:");
        int x = scanner.nextInt();
        System.out.println(x);
        if (x == 1) {
            System.out.println("Enter a string");
            //If I use "scanner" instead of "scanner2" here,
            //or if I do not create a new scanner object,
            //the program would not allow me to enter a string, 
            //and it instantly jumps to "The end".
            Scanner scanner2 = new Scanner(System.in);
            String y = scanner2.nextLine();
            System.out.println(y);
            scanner2.close();
        } else {
            System.out.println("The end.");
        } scanner.close();
    }
}
