【问题标题】:How can I make this statement (within a while-loop) not print out twice to the console?我怎样才能使这个语句(在一个while循环内)不打印到控制台两次?
【发布时间】:2014-02-24 13:53:46
【问题描述】:

我对 Java 非常陌生,(以及完全编程)。我确信我的问题的解决方案非常简单,但我就是想不通。下面的代码是我程序的一小部分。但它仍然是可编译的,并且仍然存在同样的问题。

这里是代码::

import java.util.Scanner;

public class Practice{
    public static void main(String args[]){

        Scanner input = new Scanner(System.in);

        String command = "";

        double d; // Distance
        double t; // Time
        double s; // Speed

        System.out.println("Hello, I am the Physics Calculator!!");

        while (!command.equals("end")){

            System.out.print("What would you like to calculate?: "); // after the first loop, this statement is printed twice to the screen! :(
            command = input.nextLine();
            System.out.println();

            if (command.equals("speed")){  

                System.out.print("What is the distance in meters?: ");
                d = input.nextDouble();

                System.out.print("What is the time is seconds?: ");
                t = input.nextDouble();

                s = d / t;

                System.out.println("The Speed is "+ s +" m/s");
                System.out.println();

            }
        } //End of the while-loop
    }
}

while循环中的第一行代码是:

System.out.println("What would you like to calculate?: ");

到目前为止一切顺利。当我运行程序时,它会打印:*你想计算什么?:* 然后程序按预期继续。

问题是程序到达while循环结束后,又返回到while循环的顶部。它将打印:

你想计算什么?:
你想计算什么?:

我只是想不通为什么它会打印两次。

这是我在运行程序时收到的确切输出的示例(斜体是控制台的输出,粗体是我的输入):

开始{

大家好,我是物理计算器!!
你想计算什么?:速度

距离是多少米?:50
时间是几秒?:50
速度为 1.0 m/s

您要计算什么?:
您要计算什么?:
}结束

最后,我仍然可以输入 'speed' 并继续执行该程序。我只是想摆脱第二个“你想计算什么”。

任何有关我遇到的问题的意见将不胜感激!!

感谢您非常抽出宝贵时间!

【问题讨论】:

  • 请同时考虑 Java 的编码约定。对于命名,您应该使用input 而不是Inputcommand 而不是Command
  • 谢谢伊恩!!我对 Java 的编码约定做了一些研究,你是对的!我没有遵守约定,所以我编辑了我的帖子(和我的程序),并纠正了我的错误。再次感谢!

标签: java while-loop system.out


【解决方案1】:

发生这种情况是因为nextDouble 不使用数字后面的换行符。您需要单独执行此操作。目前,下次提示您输入命令时,该换行符(在数字之后)会被使用。由于空字符串不是"speed",因此循环多执行一次。

t = Input.nextDouble(); 之后添加Input.nextLine(); 就可以了。

【讨论】:

  • 谢谢大卫!!当我按照您的建议进行操作时,它解决了问题!虽然我不得不承认,但我不明白为什么添加Input.nextLine(); 可以解决问题。但我对编程很陌生,(只有两周),我相信随着我了解更多,我会弄明白的。再次感谢!!
  • @JavaSufferer 当您按下“回车”提交时,它会在 System.in 中键入一个换行符。当您调用 nextDouble 时,Scanner 会读取一定数量的字符,这些字符是它在输入中找到的下一个数字字符串,留下任何剩余的字符。调用 nextLine 从流中读取下一行,在这种情况下,它只是 nextDouble 未读取的最后一个条目中的换行符。这只是 Scanner 和 System.in 之间的奇怪交互。
  • 是的,@Radiodef,这是一种很好的表达方式。这个网站上有很多很多关于这个完全相同的问题的问题 - 程序使用nextLinenextIntnextDouble 在同一个Scanner 上。不幸的是,如果您不知道这就是问题所在,就很难知道要搜索什么。 JavaSufferer,我建议您快速搜索“Scanner nextLine”之类的内容并阅读这些其他问题的一些答案。
猜你喜欢
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 2021-07-26
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多