问题
So I've been trying to make a simple calculator program in Java myself and I seem to have encountered a problem. The code doesn't seem to have an error (none showing in Eclipse or in Command Prompt), but when I run it it ends after you input the operation. Here's the example of my code:
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);
}
}
}
Any and all insight is appreciated.
回答1:
Use method
string.equals("string")
when comparing two strings in Java
Also start names of your classes with an upper case letter, that is a programming convention.
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);
}
}
}
来源:https://stackoverflow.com/questions/33403299/trouble-with-a-simple-calculator-code-java