简体   繁体   中英

Trouble with a simple calculator code (Java)

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.

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);
}

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM