在我的java计算器中需要帮助

时间:2016-11-19 18:05:36

标签: java calculator

我最近开始学习java,我试图编写一个计算器,但它给了我错误(我不明白它为什么会发生)。

PS:抱歉我的英文不好

package pkg2;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Write a number: ");
        int first = reader.nextInt();
        System.out.println("Write another number: ");
        int second = reader.nextInt();
        System.out.println("Write an operator: ");
        char operator = reader.nextInt();
        if(operator == '+') {
            System.out.println(first + second);
        }
        else if(operator == '-') {
            System.out.println(first - second);
        }
        else if(operator == '*') {
            System.out.println(first * second);
        }
        else if(operator == '/') {
            System.out.println(first / second);
        }
    }
}

错误是:

enter image description here

1 个答案:

答案 0 :(得分:3)

当您提示操作符时,您正在尝试读取int而不是char。这是你应该怎么做的:

package pkg2;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.println("Write a number: ");
        int first = reader.nextInt();
        System.out.println("Write another number: ");
        int second = reader.nextInt();
        System.out.println("Write an operator: ");
        char operator = reader.next().charAt(0);
        if(operator == '+') {
            System.out.println(first + second);
        }
        else if(operator == '-') {
            System.out.println(first - second);
        }
        else if(operator == '*') {
            System.out.println(first * second);
        }
        else if(operator == '/') {
            System.out.println(first / second);
        }
    }
}