简单的计算器代码(Java)有麻烦 [英] Trouble with a simple calculator code (Java)

查看:67
本文介绍了简单的计算器代码(Java)有麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}
}

任何

推荐答案

使用方法


string.equals( string)

string.equals("string")

在Java中比较两个字符串时

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

}
}

这篇关于简单的计算器代码(Java)有麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆