Simple Java calculator

后端 未结 10 1906
迷失自我
迷失自我 2020-12-22 02:16

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 c

10条回答
  •  悲哀的现实
    2020-12-22 03:10

    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:

    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.

    Hope this helps!

提交回复
热议问题