【问题标题】:How do I input a string after integers in a while loop?如何在while循环中输入整数后的字符串?
【发布时间】:2020-05-05 20:25:55
【问题描述】:

我正在尝试制作一个程序来计算某人的步数(如果数字大于或等于 10000,该程序应该停止),但我似乎找不到输入“回家”的方法",然后输入回家所需的步数。

Scanner scan = new Scanner(System.in);
        int totalSteps = 0;

        while(true)
        {
            int steps = scan.nextInt();
            totalSteps = totalSteps + steps;
            if(totalSteps >= 10000) {
                System.out.println("Goal reached! Good job!");
                break;
            }
           else if(steps < 10000)
            {
                String home = scan.nextLine();
                if(home.equals("Going home"))
                {
                    int extraSteps = scan.nextInt();
                    totalSteps = totalSteps + steps + extraSteps;
                    System.out.println(10000 - totalSteps + " more to reach goal.");
                }
            }
        }

【问题讨论】:

    标签: java string


    【解决方案1】:

    你应该看看这个:Why is nextLine() returning an empty string?

    这可行:

    else if(steps < 10000) {
                    scan.nextLine();
                    String home;
                    while (!(home = scan.nextLine()).isEmpty()) {
                        if (home.equals("Going home")) {
                            int extraSteps = scan.nextInt();
                            totalSteps = totalSteps + steps + extraSteps;
                            System.out.println(10000 - totalSteps + " more to reach goal.");
                        }
                    }
                }
    

    【讨论】:

    • 当我使用它时,在我输入额外的步骤后它会出错,它不会正确地进行计算并且程序的第一部分(达到目标的部分不再发生)是不工作
    【解决方案2】:

    这似乎是读取换行符的问题。一个简单(但可能不是最好的)解决方案如下:

            Scanner scan = new Scanner(System.in);
            scan.useDelimiter("\n");
            int totalSteps = 0;
    
            while(true)
            {
                int steps = Integer.parseInt(scan.nextLine());
                totalSteps = totalSteps + steps;
                if(totalSteps >= 10000) {
                    System.out.println("Goal reached! Good job!");
                    break;
                }
                else if(steps < 10000)
                {
                    String home = scan.nextLine();
                    if(home.equals("Going home"))
                    {
                        int extraSteps = Integer.parseInt(scan.nextLine());
                        totalSteps = totalSteps + steps + extraSteps;
                        System.out.println(10000 - totalSteps + " more to reach goal.");
                    }
                }
            }
    

    有关此问题的更多详细信息,您可以在此处查看与非常相似的问题的讨论:https://www.daniweb.com/programming/software-development/threads/232053/nextline-after-nextint-or-nextdouble-gives-trouble

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 2023-03-14
      相关资源
      最近更新 更多