1

ユーザー入力が であるかどうかを示すコードが必要ですdouble。の場合doubleは変数に格納する必要がありdegreeCelsius、そうでない場合はプログラムを終了する必要があります。全体として、プログラムはいくつかのdouble値を取り、それらを摂氏として使用し、華氏に変換します。これは私がこれまでに持っているものです:

import java.util.*;
public class Lab4b
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        double degreeCelsius = 0.0;
        double degreeFahrenheit = 0.0;
        System.out.println("Celcius    | Fahrenheit");

        while(scan.next() != null)
            {    
//this is where I need the code. If you see any other errors, feel free to correct me
            //if (degreeCelsius = Double)
                    {
                        degreeCelsius = scan.nextDouble();
                    }
                else
                    {
                        System.exit(0);
                    }
                degreeFahrenheit = degreeCelsius * (9.0/5.0) + 32.0;
            }
    }
}
4

6 に答える 6

1

double が入力されない可能性があるため、String を読み取ってから double に変換することをお勧めします。標準的なパターンは次のとおりです。

Scanner sc = new Scanner(System.in);
double userInput = 0;
while (true) {
    System.out.println("Type a double-type number:");
    try {
        userInput = Double.parseDouble(sc.next());
        break; // will only get to here if input was a double
    } catch (NumberFormatException ignore) {
        System.out.println("Invalid input");
    }
}

ループは、double が入力されるまで終了できません。その後、userInputその値が保持されます。

また、プロンプトをループ内に配置することで、無効な入力でのコードの重複を回避できることにも注意してください。

于 2013-09-18T06:36:24.347 に答える
0

以下のメソッドを使用して、入力文字列が double かどうかを確認できます。

public boolean isDouble(String inputString) {
    try {
            Double d=Double.parseDouble(inputString);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
于 2013-09-18T05:35:13.510 に答える
0

while を変更する 1 つの方法を次に示します。

    while(scan.hasNextDouble()) {
        degreeCelsius = scan.nextDouble();
        degreeFahrenheit = degreeCelsius * (9.0/5.0) + 32.0;
        System.out.println(degreeCelsius + " in Celsius is " + degreeFahrenheit + " in Fahrenheit");

    }

スキャナが入力を空白で分割するイベントでは、通常、Unix と Windows のデフォルトの端末設定により、エントリ間で Enter キーを押す必要があることに注意してください。

詳細はこちら:

Javaのコンソールから単一の文字を読み取る方法(ユーザーが入力したとき)?

于 2013-09-18T03:23:49.403 に答える