2010-12-20 237 views
0

舉個我想要使用此代碼闡述的想法是這樣的:在陣列節省運營商,錯誤

  1. 輸入兩個數字:10 7
  2. 選擇運營商:如(+, - ,*和/)
  3. 什麼是10 * 7?
  4. 正確!

    int[] arr = new int[5]; 
    
    
    System.out.println("enter two numbers: "); 
    arr[1] = sc.nextInt(); 
    arr[2] = sc.nextInt(); 
    
    
    System.out.println("Choose Operator: "); 
    arr[3] = sc.nextInt(); 
    
    
    int operator = arr[1]+arr[3]+arr[2]; 
    
    
    System.out.print("what's "+operator); 
    int svar = sc.nextInt(); 
    
    
    if (svar == operator) 
        System.out.println("Correct!"); 
    else 
        System.out.println("Wrong - the right answer is "+operator);  
    

現在我有這個代碼中運行的一些方面的問題。它工作正常,編譯但每次程序要求爲「選擇運營商」具有以下錯誤編譯迴應:

  • 異常線程「main」
    • java.util.InputMismatchException在在
    • java.util.Scanner.next
    • java.util.Scanner.throwFor(未知
    • 源)(未知
    • 源)在
    • java.util.Scanner.nextInt(未知
    • 源)在
    • java.util.Scanner.nextInt(未知
    • 源)
    • 在test1.main(TEST1。 Java的:13)

我知道我該怎麼去處理這一個。但目標是「保存」所需的操作符,然後將它與arr [1]和arr [2](在int運算符中顯示)放在一起,以「排序」創建整個數學運算。 但是,當我選擇一個特定的操作符時發生錯誤。

我希望得到這個幫助。謝謝!

+0

您正在嘗試用sc.nextInt()讀取一個字符。這聽起來不對。 – sjngm 2010-12-20 14:49:13

+0

你覺得'System.out.print(「什麼是」+運算符)'行可以打印? – SLaks 2010-12-20 14:52:53

+0

號碼,運營商,號碼。舉個例子:10 * 10 – Racket 2010-12-20 15:13:01

回答

1

首先,您試圖互換使用int s和String,這在強類型語言(例如Java)中是不可能的。其次,對於這種計算器應用程序,您應該使用堆棧。爲了最簡單的實現,爲操作員提供一個數字堆棧和一個堆棧。

1

你打電話給nextInt,它試圖讀取一個整數。
由於您未輸入整數,因此出現錯誤。

要實現您的想法,您需要一個Operator接口與int execute(int x, iny y)方法,併爲每個運算符分別設置一個類。
然後,您會從sc中讀取一個字符,並找到該字符的相應實現Operator。 (也許使用一個Map<String, Operator>

+0

這幾天你可能想使用'java.util.function.BinaryOperator'等。如果你打算用Java來做這件事。 – OrangeDog 2016-06-17 12:58:32

0

這裏

System.out.println("Choose Operator: "); 
    arr[3] = sc.nextInt(); 

你想存儲一個「+」操作符爲int,也許你應該讀行,然後決定如何處理在輸入讀做。

+0

好的,我嘗試nextLine,但它說它不能將字符串轉換爲int。所以這也行不通。 – Racket 2010-12-20 15:14:50

0

所有你需要的是兩個整數,一個字符和一個雙,如果不是使用數組,所以這是對你的代碼必須:

int num1, num2; 
double result; 
char op; 

System.out.println("enter two numbers: "); 
num1 = sc.nextInt(); 
num2 = sc.nextInt(); 

System.out.println("Choose Operator: "); 
op = System.in.read(); // Edited 

switch (op) 
{ 
    case '+': res = num1 + num2; break; 
    case '-': res = num1 - num2; break;   
    case '/': res = num1/num2; break; 
    case '*': res = num1 * num2; break; 
}  

System.out.print("what's " + num1 + op + num2); 

if (sc.nextInt() == res) 
    System.out.println("Correct!"); 
else 
    System.out.println("Wrong - the right answer is " + res);  

享受, Rotem公司

+0

嗨!非常感謝。雖然我不確定關於「op = sc.nextChar」的說法。 Eclipse不知道它是什麼,它想要將其更改爲nextInt(); – Racket 2010-12-20 15:59:48

+0

呵呵Eclipse是正確的=)它應該是「op = sc.nextLine()」,沒有nextChar方法(我剛剛閱讀Scanner API - http://download.oracle.com/javase/1.5.0/docs /api/java/util/Scanner.html)現在都很好! B.T.W它也可以使用System.in.read()來獲取單個字符.. – Rotem 2010-12-20 22:14:01