2016-12-17 8 views
-1

私はJavaに慣れていないので、電卓をコーディングしようとしています。数字は計算されていないので、なぜそれが起こっているのか分かりません。Java Rookie電卓をコード化しようとしています

import java.util.Scanner; 

public class Calculator { 
    public static void main(String[] args){ 

     System.out.println("Type in any 2 numbers: "); 
     Scanner math = new Scanner(System.in); 
     int number = math.nextInt(); 
     int num2 = math.nextInt(); 

     System.out.println("Which operation would you like to use? (+,-,*,/)"); 
     String oper = math.next(); 

     if (oper == "+"){ 
      int total = number + num2; 
      System.out.println(total); 
     } 
     else if (oper == "-"){ 
      int total = number - num2; 
      System.out.println(total); 
     } 
     else if (oper == "*"){ 
      int total = number * num2; 
      System.out.println(total); 
     } 
     else if (oper == "/"){ 
      int total = number/num2; 
      System.out.println(total); 
     } 
    } 

} 

答えて

1

あなたは文字列を比較するためにJavaでequalsメソッドを使用する必要があります。

は、ここに私のコードです。 クラスで "=="を使用すると、refrencesのみを比較し値は比較しません。 これは

public class Calculator { 
    public static void main(String[] args){ 

     System.out.println("Type in any 2 numbers: "); 
     Scanner math = new Scanner(System.in); 
     int number = math.nextInt(); 
     int num2 = math.nextInt(); 

     System.out.println("Which operation would you like to use? (+,-,*,/)"); 
     String oper = math.next(); 

     if (oper.equals("+")){ 
      int total = number + num2; 
      System.out.println(total); 
     } 
     else if (oper.equals("-")){ 
      int total = number - num2; 
      System.out.println(total); 
     } 
     else if (oper.equals("*")){ 
      int total = number * num2; 
      System.out.println(total); 
     } 
     else if (oper.equals("/")){ 
      int total = number/num2; 
      System.out.println(total); 
     } 
    } 
+0

ありがとうございました!これはうまくいった。 – Ubermench

0

@Ran Koretzkiが正しいと私はあなたのコードのための1つの可能な改善を持って修正これで動作するはずです。ユーザーからの入力を読み取り、「整数」の値に割り当てています。このコードでコンパイル時または実行時エラーが表示されない場合でも、コードには論理的な問題があります。

2つの整数を除算し、結果を整数に割り当てます。このアプローチは、2つの整数を除算しようとするとき、および余りがないときにうまく機能します。しかし、分割プロセスに余りがある場合は、この残りまたは分数を失います。これを解決するには、入力値をdouble値に読み込み、演算結果を二重に割り当てる必要があります。

関連する問題