Javaでは、valuseをまたはとして使用しながら、ユーザーの入力を例外メッセージに含めることは可能int
ですdouble
か?たとえば、数字(たとえば、5)を入力する必要がありますが、代わりに(5r)のようなファットフィンガーを入力する必要があります。
「5rを入力しましたが、数字を入力する必要があります。」などのメッセージを表示することはできますか?
ここでは、Javaで変数を出力する従来の方法を使用してみました。
try {
System.out.println();
System.out.println("Value: ");
double value = sc.nextDouble();sc.nextLine();
exec.ds.push(value);
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
この場合、私は例外メッセージに表示されようとしてvalue
います。ここで、valueはユーザーの無効な入力です。
それでvalue
エラーが発生しますcannot find symbol
。
以下は私が思いついた答えです。私がこの回答を選択した理由は、回答のほとんどが「0.0を入力しました...」という出力を生成したためです。これは、回答が最初にコンソールに出力される文字列である必要があるためです。さらに、プログラムの他の場所で数値として使用するために、文字列はDouble型またはInteger型のオブジェクトにキャストしました。
String value = null; //declared variable outside of try/catch block and initialize.
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextLine(); //Accept String as most of you suggested
Double newVal = new Double(value); //convert the String to double for use elsewhere
exec.ds.push(newVal); //doulbe is getting used where it would be a 'number' instead of string
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number"); //the String valuse is received and printed as a String here, not a 'number'
} //now prints what the users inputs...