Java 中的简单计算器程序

Simple calculator program in Java

我是 Java 的新手编码员,我正在尝试在 java 中制作此计算器,用户可以在其中输入两个数字和 select 对这些数字进行的操作数字。但是,当代码涉及到 selecting 运算符时,它会跳过用户输入和 if 语句并直接实现 else 语句。

import java.util.Scanner;


public class Calculator {

    public static void main(String[] args) {
        Scanner Calc = new Scanner(System.in);
        int n1;
        int n2;
        int Answer;

        System.out.println("Enter the first number: ");
        n1 = Calc.nextInt();
        System.out.println("Enter the second number:" );
        n2 = Calc.nextInt();
        System.out.println("Select the order of operation: ");
        char operator = Calc.nextLine().charAt(0);


        if (operator == '+') {
            Answer = (n1 + n2);
            System.out.println("Answer:" + Answer);
            } 
        if (operator == '-') {
            Answer = (n1 - n2);
            System.out.println("Answer:" + Answer);
            } 
        if (operator == '*') {
            Answer = (n1 * n2);
            System.out.println("Answer:" + Answer);
            } 
        if (operator == '/') {
            Answer = (n1/n2);
            System.out.println("Answer:" + Answer);
            } 
        else {
            System.out.println("not implemented yet. Sorry!");
        }


    }

}

n2 = Calc.nextInt(); 之后添加 Calc.nextLine(); 以消耗换行。

你也没有使用 else if 所以所有这些 if 条件将被检查,即使之前的 if 已经匹配(导致你的最终 else 只要运算符不被执行'/').

在这种情况下,您可能应该只使用 switch 块。

我对代码做了一些修改,这应该适合你,但我也建议使用一个开关。

扫描仪输入 = 新扫描仪(System.in);

    try {
        System.out.print("Enter a number: ");
        int num1 = Input.nextInt();

        System.out.print("Enter an operator: ");
        char operator = Input.next().charAt(0);

        System.out.print("Enter a second number: ");
        int num2 = Input.nextInt();
        // this part of decision, it doesn't work.
        if ('+' == operator) {
            System.out.println("Your result is " + (num1 + num2));
        } else if ('-' == operator) {
            System.out.println("Your result is " + (num1 - num2));
        } else if ('*' == operator) {
            System.out.println("Your result is " + (num1 * num2));
        } else if ('/' == operator) {
            System.out.println("Your result is " + (num1 / num2));
        }else {
            System.out.println("Your answer is not valid");
        }
    } catch (InputMismatchException e) {
        System.out.println("similar to try and except in Python");
    }