【问题标题】:Stuck While Loop (Java)卡住 While 循环 (Java)
【发布时间】:2020-03-01 11:14:40
【问题描述】:

全部! 我是一名大学一年级计算机科学专业的学生,​​正在学习编程课程。在做作业时,我卡在了代码的某个部分。请善待,因为这是我的第一个学期,我们才学 Java 3 周。

就上下文而言,我的任务是: “创建一个程序,要求用户输入他们的姓名并输入他们一天中步行的步数。然后询问他们是否要继续。如果答案是“是”,请他们输入另一个步数走。再次询问他们是否要继续。如果他们输入“是”以外的任何内容,您应该告诉他们“再见,[NAME]”以及他们输入的步数总和来结束程序。”

为了我的一生,我无法让 while 循环结束。它忽略了我(可能以不正确的方式)设置的条件。

你能帮我告诉我我做错了什么吗?

import java.util.Scanner;

public class StepCounter 
{

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) 
    {
        final String SENTINEL = "No";

        String userName = "";
        String moreNum = "";
        int numStep = 0;
        int totalStep = 0;
        boolean done = false;
        Scanner in = new Scanner(System.in);
        Scanner in2 = new Scanner(System.in);

        // Prompt for the user's name
        System.out.print("Please enter your name: ");
        userName = in.nextLine();

        while(!done)
        {
            // Prompt for the number of steps taken
            System.out.print("Please enter the number of steps you have taken: ");
            // Read the value for the number of steps
            numStep = in.nextInt();
            // Prompt the user if they want to continue
            System.out.print("Would you like to continue? Type Yes/No: ");
            // Read if they want to continue
            moreNum = in2.nextLine();
            // Check for the Sentinel
            if(moreNum != SENTINEL)
            {
                // add the running total of steps to the new value of steps
                totalStep += numStep;
            }
            else
            {
                done = true;
                // display results
                System.out.println("Goodbye, " + userName + ". The total number of steps you entered is + " + totalStep + ".");
            }
        }
    }

}

【问题讨论】:

  • 尝试使用调试器并查看循环中的内容
  • 我还不知道如何使用调试器。 ):
  • 作业说你应该勾选“是”继续,而不是“否”停止
  • 您使用什么类型的 idi 或编辑器来编写代码?
  • Netbeans 因为我必须这样做。

标签: java loops while-loop infinite-loop


【解决方案1】:

要比较 String 对象的内容,您应该使用 compareTo 函数。

moreNum.compareTo(SENTINEL) 如果相等则返回 0。

== 运算符用于检查它们是否引用相同的对象。

还有一个添加步骤的问题,如果输入“否”也应该添加

【讨论】:

    【解决方案2】:

    使用

    if(!moreNum.equals(SENTINEL))
    

    而不是

    if(moreNum != SENTINEL)
    

    另外,请确保将:totalStep += numStep; 添加到您的 else 语句中,以便您的程序实际上将这些步骤添加在一起。

    【讨论】: