首页 > 解决方案 > 如何在while循环中输入整数后的字符串?

问题描述

我正在尝试制作一个程序来计算某人的步数(如果数字大于或等于 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.");
                }
            }
        }

标签: javastring

解决方案


你应该看看这个:为什么 nextLine() 返回一个空字符串?

这会起作用:

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.");
                    }
                }
            }

推荐阅读