【问题标题】:User input skipped in the Output [duplicate]输出中跳过的用户输入[重复]
【发布时间】:2018-11-15 15:36:56
【问题描述】:

那里会有多少客人? 4

输入客人 1 的选择

输入客人 2 的选择


在我输入客人数量后,客人 1 和 2 正好落在彼此之下,我没有机会输入客人 1 的选择,它转到客人 2。 我该如何解决这个问题?

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

        int guest;
        String choice;
        System.out.println("Welcome to Tying the Knot Wedding Planner Guide");
        System.out.println();
        System.out.println("For each guest, please enter he/her choice for dinner: Beef, Chicken, Fish, or\r\n" + 
                "Vegetarian.\r\n" + 
                "");
        System.out.print("How many guests will there be there? ");
        guest=simpleInput.nextInt();

        while (guest <0 )
        {
            System.out.println ( "That was not a valid number, try again. " );
            System.out.println("How many guests will there be there? ");
            guest=simpleInput.nextInt();
        }

        for (int x = 1; x < guest; x++ )
        {
        System.out.println("Enter the choice for guest  " + x);
        choice=simpleInput.nextLine();
        }

        System.out.println("There will be " + guest + " meals");
    }

【问题讨论】:

标签: java output


【解决方案1】:

请更改您的代码

guest=simpleInput.nextInt();

guest=Integer.parseInt(simpleInput.nextLine());

这将帮助您解决问题

【讨论】:

  • 这个问题已经在评论区解决了
【解决方案2】:

当您使用.nextInt( 方法时,扫描仪会读取并解析文本,直到换行符 (\n),因此当再次尝试使用任何读取方法时,扫描仪不为空(它具有 \n 字符) 这就是为什么它假设用户确实输入了另一个字符串 您可以通过多种方式克服这个问题,一种是通过在 .nextInt() 之后再添加一行来简单地从扫描仪中删除 /n

simpleInput.nextline();

另一种方法是获取整行,然后从中解析出 int,不留 /n 字符

guests = Integer.parseInt(simpleInput.nextLine());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 2016-02-05
    • 2021-11-29
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多