麻烦一个简单的计算器代码(Java)

时间:2015-10-28 23:20:58

标签: java calculator

所以我一直在努力用Java编写一个简单的计算器程序,而我似乎遇到了一个问题。代码似乎没有错误(没有在Eclipse或命令提示符中显示),但是当我运行它时它会在您输入操作后结束。这是我的代码示例:

public class vjezba1
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
Scanner text=new Scanner(System.in);

String opr;
int x;
int y;
int sum;

System.out.println("This is a simple calculator program.");
System.out.println("Input first number: ");
x = input.nextInt();

System.out.println("Input second number: ");
y = input.nextInt();

System.out.println("Choose an operation (+,-,*,/): ");
opr = text.nextLine();

if(opr == "+"){
    sum = x + y;
    System.out.println("Result is: " + sum);
}else if(opr == "-"){
    sum = x - y;
    System.out.println("Result is: " + sum);
}else if(opr == "*"){
    sum = x * y;
    System.out.println("Result is: " + sum);
}else if(opr == "/"){
    sum = x / y;
    System.out.println("Result is: " + sum);
}

}
}

赞赏任何和所有见解。

1 个答案:

答案 0 :(得分:1)

使用方法

  

string.equals( “串”)

比较Java中的两个字符串

还可以使用大写字母来启动类的名称,这是一种编程约定。

http://www.oracle.com/technetwork/java/codeconventions-135099.html

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

public class Vjezba1
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
Scanner text=new Scanner(System.in);

String opr;
int x;
int y;
int sum;

System.out.println("This is a simple calculator program.");
System.out.println("Input first number: ");
x = input.nextInt();

System.out.println("Input second number: ");
y = input.nextInt();

System.out.println("Choose an operation (+,-,*,/): ");
opr = text.nextLine();
System.out.print(opr);
if(opr.equals("+")){
    sum = x + y;
    System.out.println("Result is: " + sum);
}else if(opr.equals("-")){
    sum = x - y;
    System.out.println("Result is: " + sum);
}else if(opr.equals("*")){
    sum = x * y;
    System.out.println("Result is: " + sum);
}else if(opr.equals("/")){
    sum = x / y;
    System.out.println("Result is: " + sum);
}

}
}