【问题标题】:Simple calculator program in JavaJava中的简单计算器程序
【发布时间】:2016-05-14 06:12:03
【问题描述】:

我是 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!");
        }


    }

}

【问题讨论】:

标签: java java.util.scanner calculator calc


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    扫描仪输入 = 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");
        }
    

    【讨论】:

      猜你喜欢
      • 2013-11-29
      • 1970-01-01
      • 2013-06-27
      • 2011-02-13
      • 2012-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      相关资源
      最近更新 更多