Trouble with a simple calculator code (Java)

空扰寡人 提交于 2019-12-14 03:00:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!