用户输入-扫描仪跳过用户输入

时间:2019-10-22 08:54:45

标签: java

这是我为程序的用户输入所做的简单测试,但是它跳过了第二个用户输入部分。我正在使用sc.nextLine()

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    int option;
    String name;

    System.out.println("1 or 2");
    option = sc.nextInt();

    if(option == 1)
    {
        System.out.println("Please enter a name");
        name = sc.nextLine();
        System.out.println(name);
    }
}

2 个答案:

答案 0 :(得分:0)

在代码中sc.nextLine()之后使用sc.nextInt()

答案 1 :(得分:0)

问题在于,第一个用户输入的回车(“ \ n”)不是数字,而用于第二个。 解决此问题的快捷方法是添加“ sc.nextLine();”。在“ nextInt()”行之后。 喜欢:

    public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    int option;
    String name;

    System.out.println("1 or 2");
    option = sc.nextInt();
    sc.nextLine();

    if(option == 1)
    {
        System.out.println("Please enter a name");
        name = sc.nextLine();
        System.out.println(name);
    }
}