簡體   English   中英

如何在while循環中輸入整數后的字符串?

[英]How do I input a string after integers in a while loop?

我正在嘗試制作一個程序來計算某人的步數(如果數字大於或等於 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.");
                }
            }
        }

你應該看看這個: 為什么 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.");
                    }
                }
            }

這似乎是閱讀換行符的問題。 一個簡單(但可能不是最好的)解決方案如下:

        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-給麻煩

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM