2017-04-22 74 views
-1

這裏是我的計算器程序如何糾正這個計算器程序?

/*program calculator */ 
import java.util.Scanner; 
class calculator 

    { public static void main (String args[]) 
    { System.out.println("First enter two number , then type Sum for addition, Sub for subtraction, Mul for multiplication, Div for division"); 
     int x, y; 
     Scanner in = new Scanner(System.in); 
     System.out.println("Enter 1st number"); 
     x = in.nextInt(); 
       System.out.println("Enter 2nd number"); 
     y = in.nextInt(); 
       System.out.println("Enter Sum for addition, Sub for subtraction, Mul for multiplication, Div for division"); 
     String z = in.next(); 
     if (z = "Sum") {a = x + y;}; 
     if (z = "Sub") {a = x - y;}; 
     if (z = "Mul") {a = x * y;}; 
     if (z = "Div") {a = x/y;}; 
     System.out.println("Result of entered two number = "+z); 
    } 
} 

它顯示在聲明中if (z = "Sum") {a = x + y;};一個錯誤「不兼容的類型」,我認爲它必須有更多的錯誤。我是一名初學者。我想使這個程序完美無誤,所以它像一個小型計算器一樣工作。

回答

0

你可以使用 '==' 比較 (並打印結果的不Z)

if (z.equals("Sum")) {a = x + y;}; 
if (z.equals("Sub")) {a = x - y;}; 
if (z.equals("Mul")) {a = x * y;}; 
if (z.equals("Div")) {a = x/y;}; 
System.out.println("Result of entered two number = " + a); 
+0

謝謝user3804188 – bhavik13