2014-11-14 18 views
0

在下面的JAVA代碼Mul和Add運算符不工作只有X-y運算符結果我得到請請教如何找到這個問題的答案。請給出這個回答,如果循環只有x-y正在工作

public class oppswithvalue { 

void calculate(int x,int y,String op) 
{ 
    //System.out.println(op); 


    if(op=="*") 
     System.out.println("X x Y : "+(x*y)); 
    else if(op=="+") 
     System.out.println("X + Y : "+(x*y)); 
    else 
     System.out.println("X - Y : "+(x-y)); 
} 

public static void main(String args[]) throws IOException 
{ 

    BufferedReader ar=new BufferedReader(new InputStreamReader(System.in)); 
    System.out.println("Enter first number : "); 
    int no1=Integer.parseInt(ar.readLine()); 
    System.out.println("Enter Second number : "); 
    int no2=Integer.parseInt(ar.readLine()); 
    System.out.println("Enter an operator : "); 
    String op=ar.readLine(); 

    oppswithvalue tt= new oppswithvalue(); 
    tt.calculate(no1, no2,op); 
} 

} 
+0

的[我如何在Java中比較字符串?]可能重複(http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Kenster

回答

6

在Java中,你不==比較字符串,您使用equalsmore):

if(op.equals("*")) 

如果你在switch語句中使用Java 7或更高版本,可以使用字符串,這對於這樣的運算符列表是有意義的:

switch (op) { 
    case "*": 
     System.out.println("X x Y : "+(x*y)); 
     break; 
    case "+": 
     System.out.println("X + Y : "+(x+y)); // <== Also see note below 
     break; 
    default: 
     System.out.println("X - Y : "+(x-y)); 
     break; 
} 

這不會在Java 6及更早版本中編譯。

另外,as Bobby points out in a comment,你在哪裏,你要在+操作+if/else if*。 (它在上面的switch中得到糾正。)

0

正如其他人指出的那樣。比較對象時,應該使用.equals()而不是==。 (String是Java中的一個對象)。

使用==只對原始數據類型,如比較:intchardouble ...等

因爲你的操作是單個字符,您的代碼仍然可以,如果你從改變操作者的工作類型Stringchar

void calculate(int x,int y, char op) 
{ 
    //Your codes 
} 
0

在java中,==不能用於比較字符串。改用.equals()方法。

if(op.equals("*")) 
    System.out.println("X x Y : "+(x*y)); 
else if(op.equals("+")) 
    System.out.println("X + Y : "+(x*y)); 
else 
    System.out.println("X - Y : "+(x-y)); 
相關問題