Java中的简单计算器程序

时间:2016-02-04 14:56:41

标签: java java.util.scanner calculator calc

我是Java中的新手编码器,我正在尝试在java中创建这个计算器,用户可以在其中输入两个数字并选择要对这些数字执行的操作。但是,当代码选择运算符时,它会跳过用户输入和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!");
        }


    }

}

2 个答案:

答案 0 :(得分:1)

Calc.nextLine();之后添加n2 = Calc.nextInt();以使用换行符。

您也没有使用else if,因此即使之前的if已经匹配,也会检查所有这些if条件(导致您的最终其他条件执行只要运算符不'/' 1}})。

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

答案 1 :(得分:0)

我对代码进行了一些更改,这应该适用于您,但我也建议使用开关。

Scanner Input = new Scanner(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");
    }