简单的Java计算器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2734227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:16:04  来源:igfitidea点击:

Simple Java calculator

javacalculator

提问by lemon

Firstly this is not a homework question. I am practicing my knowledge on java. I figured a good way to do this is to write a simple program without help. Unfortunately, my compiler is telling me errors I don't know how to fix. Without changing much logic and code, could someone kindly point out where some of my errors are? Thanks

首先,这不是家庭作业问题。我正在练习我的Java知识。我想一个很好的方法是在没有帮助的情况下编写一个简单的程序。不幸的是,我的编译器告诉我错误,我不知道如何修复。在不改变太多逻辑和代码的情况下,有人可以指出我的一些错误在哪里吗?谢谢

import java.lang.*;
import java.util.*;

public class Calculator
{
    private int solution;
    private int x;
    private int y;
    private char operators;

    public Calculator()
    {
        solution = 0;
        Scanner operators = new Scanner(System.in);
        Scanner operands = new Scanner(System.in);
    }

    public int addition(int x, int y)
    {
       return x + y;
    }
    public int subtraction(int x, int y)
    {
       return x - y;
    }
    public int multiplication(int x, int y)
    {    
       return x * y;
    }
    public int division(int x, int y)
    {
       solution = x / y;
       return solution;
    }
    public void main (String[] args)
    {
      System.out.println("What operation? ('+', '-', '*', '/')"); 

      System.out.println("Insert 2 numbers to be subtracted");
       System.out.println("operand 1: ");
       x = operands;
       System.out.println("operand 2: ");
       y = operands.next();
      switch(operators)
      {
          case('+'):
            addition(operands);
            operands.next();
            break;
          case('-'):
            subtraction(operands);
            operands.next();
            break;
          case('*'):
            multiplication(operands);
            operands.next();
            break;
          case('/'):
            division(operands);
            operands.next();
            break;
       }
  }
}

采纳答案by gmhk

package org.com;

import java.lang.*; 
import java.util.*; 

public class Calculator 
{ 
    private int solution; 
    private static int x; 
    private static int y; 
    private char operators; 

    public Calculator() 
    { 
        solution = 0; 
        Scanner operators = new Scanner(System.in); 
        Scanner operands = new Scanner(System.in); 
    } 

    public int addition(int x, int y) 
    { 
       return x + y; 
    } 
    public int subtraction(int x, int y) 
    { 
       return x - y; 
    } 
    public int multiplication(int x, int y) 
    {     
       return x * y; 
    } 
    public int division(int x, int y) 
    { 
       solution = x / y; 
       return solution; 
    } 

    public void calc(int ops){
         x = 4; 
         System.out.println("operand 2: "); 
         y = 5; 

         switch(ops) 
         { 
             case(1): 
               System.out.println(addition(x, y)); 

           //    operands.next(); 
               break; 
             case(2): 
                 System.out.println(subtraction(x, y)); 
              // operands.next(); 
               break; 
             case(3): 
                 System.out.println(multiplication(x, y)); 
             //  operands.next(); 
               break; 
             case(4): 
                 System.out.println(division(x, y));
             //  operands.next(); 
               break; 
          } 
    }
    public static void main (String[] args) 
    { 
      System.out.println("What operation? ('+', '-', '*', '/')");  
      System.out.println(" Enter 1 for Addition");
      System.out.println(" Enter 2 for Subtraction");
      System.out.println(" Enter 3 for Multiplication");
      System.out.println(" Enter 4 for Division");

       Calculator calc = new Calculator();
       calc.calc(1);


  } 
} 

This will work

这将工作

回答by duffymo

operandsand operatorsare out of scope for main. You declare local variables in the constructor, so when you exit the ctor they're eligible for GC and gone.

operands并且operators超出了 main 的范围。您在构造函数中声明局部变量,因此当您退出构造函数时,它们有资格进行 GC 并消失。

You have compilation errors - 10 of them.

您有编译错误 - 其中 10 个。

回答by Lars Andren

Your main method needs to be declared like this:

您的主要方法需要像这样声明:

public static void main(String[] args) {..}

Furthermore, it seems like you are only supplying one argument to your all your arithmetic methods (addition, subtraction etc), although they require two.

此外,您似乎只为所有算术方法(加法、减法等)提供一个参数,尽管它们需要两个。

public int addition(int x, int y);

Can not be called with addition(operands), that is only one argument, and the argument is of the wrong type (the method needs two int, you give it a Scanner). The same goes for all those methods. You need to extract the ints from the Scanner. You can do that with Scanner.nextInt().

不能用 调用addition(operands),那只有一个参数,而且参数类型错误(方法需要两个int,你给它一个Scanner)。所有这些方法也是如此。您需要intScanner. 你可以用Scanner.nextInt().

回答by coobird

Another issue is, the line

另一个问题是,线

y = operands.next();

is attempting to place a Stringreturned from Scanner.next()into the a variable ywhich is declared as a type int.

试图将String返回Scanner.next()的 a 放入y声明为 type的变量中int

The Scanner.nextInt()method can be used to attempt to return an int.

Scanner.nextInt()方法可用于尝试返回一个int.

回答by Yann Ramin

In addition to the other answers, your main() method must be static in order to be a program entry point. In main() you will need to construct your own Calculator object, and call methods on that.

除了其他答案之外,您的 main() 方法必须是静态的才能成为程序入口点。在 main() 中,您需要构建自己的 Calculator 对象,并在其上调用方法。

回答by Jazzy Josh

Just as a tip, it's generally not a good idea to start throwing

作为一个提示,开始投掷通常不是一个好主意

import java.util.*;
进入你的程序,因为它使程序不必要地大而慢。你所需要的只是
import java.util.Scanner;
如果我是对的,java.lang 中的大部分内容(如果不是所有内容)都已为您导入。

回答by Shashank T

package com.abc;

import java.util.Scanner;

public class Calculator {
    private static final String pos = "+";
    private static final String neg = "-";
    private static final String mult = "*";
    private static final String div = "/";

    private enum operation {
        pos, neg, mult, div
    };
    private int solution;
    private int x;
    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    private int y;



    static Scanner operators;

    public Calculator() {
        solution = 0;
        operators = new Scanner(System.in);

    }

    public int addition(int x, int y) {
        return x + y;
    }

    public int subtraction(int x, int y) {
        return x - y;
    }

    public int multiplication(int x, int y) {
        return x * y;
    }

    public int division(int x, int y) {
        solution = x / y;
        return solution;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();

        System.out.println("Insert 2 numbers");

        System.out.println("operand 1: ");

        calc.setX(Integer.parseInt(operators.next()));

        System.out.println("operand 2: ");
        calc.setY(Integer.parseInt(operators.next()));

        System.out.println("What operation? ('pos', 'neg', 'mult', 'div')");
        operation ttt = operation.valueOf(operators.next());
        int output = 0 ;
        switch(ttt){
        case pos:
            output = calc.addition(calc.getX(), calc.getY());

            break;
          case neg:
              output = calc.subtraction(calc.getX(), calc.getY());

            break;
          case mult:
              output = calc.multiplication(calc.getX(), calc.getY());

            break;
          case div:
              output = calc.division(calc.getX(), calc.getY());

            break;
        }
        System.out.println("output ="+output);
    }
}

回答by Dan299

This is all great, but what program are you using to write your java? Maybe you should consider using an IDE like Eclipse, as it can detect errors automatically and also adds imports. (I'm not sure if yours does this) It also tells you what the problem with your program is 'in english'. Also, consider this class as maybe an easier and less complicated way of doing a calculator:

这一切都很棒,但是您使用什么程序来编写 Java?也许您应该考虑使用 Eclipse 之类的 IDE,因为它可以自动检测错误并添加导入。(我不确定你的是否这样做)它还告诉你你的程序的问题是“英语”。另外,考虑这个类可能是一种更简单、更简单的计算器方式:

public class Calculator {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter an Operator: ");
    String in = sc.next();
    char oper = in.charAt(0);

    System.out.print("Enter a number: ");
    in = sc.next();
    double num1 = Double.parseDouble(in);

    System.out.print("Enter another number: ");
    in = sc.next();
    double num2 = Double.parseDouble(in);

    if(oper == '+') {
        double result = num1 + num2;
        System.out.println(result);
    } else if(oper == '-') {
        double result = num1 - num2;
        System.out.println(result);
    } else if(oper == 'x') {
        double result = num1 * num2;
        System.out.println(result);
    } else if(oper == '/') {
        double result = num1 / num2;
        System.out.println(result);
    } else {
        double result = num1 % num2;
        System.out.println(result);
    }
        System.out.println("Hope this helped your mathmatical troubles!");
}

}
And as a matter of habit, instead of doing:

}
而作为一个习惯问题,而不是在做,:

import java.util.*;

it is better to do:

最好这样做:

import java.util.Scanner;

This probably doesn't make much of a difference here, but if you are running a much bigger program importing the whole of java.util will considerably slow down your program.

这在这里可能没有太大区别,但是如果您正在运行一个更大的程序,则导入整个 java.util 会大大减慢您的程序速度。

Hope this helps!

希望这可以帮助!

回答by Waruna Wishwanath Usgoda

import java.lang.*;

import java.util.*;


public class Calculator
{
    private int solution;
    private int x;
    private int y;
 private char operators;

    public Calculator()
    {
        solution = 0;
        Scanner operators = new Scanner(System.in);
        Scanner operands = new Scanner(System.in);
    }

    public int addition(int x, int y)
    {
       return x + y;
    }
    public int subtraction(int x, int y)
    {
       return x - y;
    }
    public int multiplication(int x, int y)
    {    
       return x * y;
    }
    public int division(int x, int y)
    {
       solution = x / y;
       return solution;
    }
    public void main (String[] args)
    {
      System.out.println("What operation? ('+', '-', '*', '/')"); 

      System.out.println("Insert 2 numbers to be subtracted");
       System.out.println("operand 1: ");
       x = operands;
       System.out.println("operand 2: ");
       y = operands.next();
      switch(operators)
      {
          case('+'):
            addition(operands);
            operands.next();
            break;
          case('-'):
            subtraction(operands);
            operands.next();
            break;
          case('*'):
            multiplication(operands);
            operands.next();
            break;
          case('/'):
            division(operands);
            operands.next();
            break;
       }
  }
}

回答by Lopes_CP_113013

You are asking for the user to type in integers, but you put the statement operands.next();as the input. Try to keep consistent with your variables and user input, so changing it to operands.nextInt()would help.

您要求用户输入整数,但您将语句operands.next();作为输入。尽量与您的变量和用户输入保持一致,因此将其更改为operands.nextInt()会有所帮助。