java - 卡住的 While 循环 (Java)

标签 java loops while-loop infinite-loop

全部! 我是一名计算机科学专业的大学新生,正在学习编程类(class)。在做作业时,我被代码的某个部分卡住了。请善待,因为这是我的第一个学期,我们只学了 3 周的 Java。

就上下文而言,我的任务是: “创建一个程序,要求用户输入他们的姓名并输入他们一天行走的步数。然后询问他们是否要继续。如果答案是"is",请他们输入另一个步数走了。再次询问他们是否要继续。如果他们输入除"is"之外的任何内容,您应该通过告诉他们“再见,[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 + ".");
            }
        }
    }

}

最佳答案

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

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

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

关于添加步骤的另一个问题,如果还输入“否”,则应进行添加

关于java - 卡住的 While 循环 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58705269/

相关文章:

java - 如何将十六进制转换为base64

java - 自动Java流程图生成器

javascript - 向元素添加函数时保留 "i"值

loops - 循环遍历表并在 SAS 中加入它们

c - float变量不满足条件(C)

java - FXMLLoader.load(url) 抛出的 IOException 将不会被捕获

java - 如何修复 "double printing when I clicked twice on the pretty dialog button"

javascript - 使用循环构建对象数组并使用来自相同迭代的计算

Java Combat Simulator - 我想模拟 1000 场战斗,以跟踪英雄获胜/失败的次数

swift - 在 While Loop Swift 中更新标签