簡體   English   中英

如何將此語句(在while循環中)不打印兩次到控制台?

[英]How can I make this statement (within a while-loop) not print out twice to the console?

我是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米/秒

你想要計算什么?:
你想要計算什么?:
}結束

最后,我仍然可以輸入“速度”並繼續使用該程序。 我只是想擺脫第二個'你想要計算什么'。

關於我遇到的問題的任何意見將受到高度贊賞!

非常感謝您的時間!

發生這種情況是因為nextDouble不使用該數字后面的換行符。 你需要單獨做。 目前,下次提示您輸入命令時,該換行符(在號碼之后)將被消耗。 由於空字符串不是"speed" ,循環會經過一個額外的時間。

添加Input.nextLine(); t = Input.nextDouble(); 這將工作得很好。

暫無
暫無

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

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