卡住循环(Java)

全部! 我是大学一年级计算机科学专业,正在学习编程课程。在做作业问题时,我陷入了代码的某个部分。请好心,因为这是我的第一学期,而且我们只使用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 + ".");
            }
        }
    }

}
yjygxy123 回答:卡住循环(Java)

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

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

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

又增加了一个步骤,如果还输入了“否”,则应该进行添加

,

使用

if(!moreNum.equals(SENTINEL))

代替

if(moreNum != SENTINEL)

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

本文链接:https://www.f2er.com/3161997.html

大家都在问