不知何故,我讓操作員回圈直到我得到正確的輸入。當我嘗試將 num1 或 num2 放入“if”陳述句時,它說我無法將“int”轉換為“boolean”。請幫忙
public class main {
public static void main(String[] args) {
int num1;
int num2;
String operator;
Scanner scan = new Scanner(System.in);
System.out.print("tell me first number: ");
num1 = scan.nextInt(); //<--input only numbers, loop if not
System.out.print("tell me second number: ");
num2 = scan.nextInt(); //<--input only numbers, loop if not
//////////////////operator////////////////////////
System.out.print("tell me operator: ");
operator = scan.next();
while(true) {
if(operator.equals(" ")) {
System.out.println("answer is: " (num1 num2));
break;
}
else if(operator.equals("-")) {
System.out.println("answer is: " (num1 - num2));
break;
}
else if(operator.equals("*")) {
System.out.println("answer is: " (num1 * num2));
break;
}
else if(operator.equals("/")) {
System.out.println("answer is: " (num1 / num2));
break;
}
else {
System.out.print("wrong input! try again!: ");
operator = scan.next();
}
}
}
}
uj5u.com熱心網友回復:
嘗試這個。
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
uj5u.com熱心網友回復:
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
有了這個,錯誤的答案一直回圈直到我得到正確的輸入,但我無法讓它列印我“錯誤的輸入!再試一次!: ”錯誤的輸入沒有開始無限回圈,所以我試圖編輯并想出這個。
//////////////////first number////////////////////
System.out.print("tell me first number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong Input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num1 = scan.nextInt();
//////////////////second number///////////////////
System.out.print("tell me second number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num2 = scan.nextInt();
不知何故它幫助了大聲笑。感謝@英語は苦手的幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534277.html
