割り当てのためには、ユーザーからの入力を得るためにSystem.in.read()を使用する必要があります。私は、ユーザーがそれを終了することを決定するまで、複数回使用できる電卓を作らなければなりません。コードは引き続きJavaを使用してSystem.in.read()からの入力を受け取ります
while(!stop) {
System.out.println("Enter the first digit.");
first = askForNumber();
System.out.println("Enter the second digit.");
second = askForNumber();
System.out.println("Enter the operation to perform");
operation = askForCharacter();
if(first == 0 && first == second) {
System.out.println("Calculator closing.");
stop = true;
}
if(operation == '+') {
System.out.println(first + second);
}
else if(operation == '-') {
System.out.println(first - second);
}
else if(operation == '*') {
System.out.println(first * second);
}
else if(operation == '/') {
if(second == 0) {
System.out.println("Cannot divide by zero.");
System.out.println("Calculator closing.");
stop = true;
}
System.out.println(first/second);
}
else {
System.out.println("Not an operation");
}
}
しかし、私は、私はこのエラーを取得するプログラム実行します。
45
Enter the second digit.
pls enter number
45
Enter the operation to perform
+
90.0
Enter the first digit.
pls enter number
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.<init>(Unknown Source)
at lopezProject.LopezProject.askForNumber(LopezProject.java:17)
at lopezProject.Calculator.main(Calculator.java:13)
編集(askForNumberのコード()):あなたはInteger
に渡すcByte
で
public static double askForNumber() throws java.io.IOException {
char cByte;
String entireNumber = "";
Integer n = 0;
System.out.println("pls enter number");
while(true) { //while the user is still entering information
cByte = (char)System.in.read(); //each byte is being turned into a character
if ((cByte == ' ') || (cByte == '\n')) {
break;
}
if(java.lang.Character.isDigit(cByte)) {
entireNumber += cByte; //and added to the str string
}
}
if(entireNumber != "") {
n = new Integer(entireNumber.trim()); //turning the string into an integer
}
return (double)n.intValue();
}
public static char askForCharacter() throws java.io.IOException {
return (char)System.in.read();
}
また、askForNumber()のコードを追加する必要があります – Reek
なぜコンソールの一点に "pls enter number"と書かれていますか?それは入力ですか? askForNumber()から来ている@ aleb2000の – aleb2000
とバグは、Reekが指摘しているようにそのメソッドにもあります。 – Jan