2015-07-12 148 views
0

當我運行我的代碼時,它會正常工作,直到它提出問題「您想要使用哪種操作(sum,subst,multi,div)」。無論用戶選擇什麼,我的程序都沒有迴應!這個非常簡單的代碼有什麼問題

這是怎麼發生的?

import java.util.Scanner; 
import java.io.*; 

public class three3 { 
    public static void main (String[] args) { 
     int x; 
     int y; 
     int opera; 
     String oper; 

     Scanner in = new Scanner (System.in); 
     System.out.println(" write the first number "); 
     x = in.nextInt(); 

     System.out.println(" write the second number "); 
     y = in.nextInt(); 

     System.out.println(" which operation do you want to use from (sum , subst , multi , div)"); 
     oper = in.nextLine(); 

     if (oper == "sum") { 
      opera=x+y; 
      System.out.println(" the sum of two numbers is " + opera); 
     } 

     if (oper == "subst") { 
      opera = x - y; 
      System.out.println(" the subtraction of two numbers is " + opera); 
     } 

     if (oper == "multi") { 
      opera = x * y; 
      System.out.println(" the multi of two numbers is " + opera); 
     } 

     if (oper == "div") { 
      opera = x/y; 
      System.out.println(" the division of two numbers is " + opera); 
     } 
    } 
} 

回答

3

因爲沒有這些if-clause被執行。 您在比較Strings==這是錯誤的。改爲使用oper.equals("sum")。請參閱this question以供參考。對你的結論是總是使用equalsStrings

+1

這不是正確的答案 – gurghet

+1

@gurghet我錯過了胡安的回答中的錯誤,但是我正在接受的觀點仍然是意外行爲的一個原因。 – runDOSrun

+0

沒有*錯誤的*迴應。有*沒有*回覆 – gurghet

0

加上其他人的觀點,你也應該考慮使用else if{}else{}聲明,這樣你可以捕獲無效輸入。

2

您需要在最後一次致電in.nextInt()後立即致電in.nextLine()原因是隻要求下一個整數不會消耗輸入中的整行,因此您需要跳到下一個換行符在輸入中通過調用in.nextLine()

int y = in.nextInt(); 
in.nextLine(); 

這幾乎是每一個有你需要調用一個不消耗整條生產線的方法,後得到一個新的行時間來完成,例如,當你調用nextBoolean()

另外如,則不檢查與==運算符的字符串是否相等,而是使用.equals()字符串方法。

+0

這是正確的答案 – gurghet

1

問題在於,in.nextLine()消耗了在輸入int後單擊Enter鍵時隱式插入的\ n。這意味着該程序不會期望來自用戶的任何其他輸入。爲了解決這個問題,你可以消耗與in.nextLine()新的放線之前,詮釋你的實際變量,像這樣:

System.out.println(" write the second number "); 
y=in.nextInt(); 

System.out.println(" which operation do you want to use from (sum , subst , multi , div)"); 

in.nextLine(); //New line consuming the \n 

oper=in.nextLine(); 

if(oper.equals("sum")){//replace == by .equals 
    opera=x+y; 
} 

除此之外,和runDOSrun說,你應該從a==ba.equals(b)替換字符串的比較

+0

這也是對的 – gurghet

相關問題