Java:纠错码计算器

时间:2012-09-17 01:26:51

标签: java calculator

如何纠正行中的错误

char oper = entrada.next(); //ERROR HERE

代码:

/*
 * Calculator
 */
package list01;

import java.util.Scanner;

public class ex04 {

    public void metodoEx04() {
        Scanner entrada = new Scanner(System.in);
        System.out.print("First number: ");
        int A = entrada.nextInt();
        System.out.print("Second number: ");
        int B = entrada.nextInt();
        System.out.print("Operator +, -, *, ou /: ");
        char oper = entrada.next(); //ERROR HERE
        double res = calculadora(A, B, oper);
        System.out.println(res);
    }

    static double calculadora(int n1, int n2, char operador) {
        double res;
        switch (operador) {
            case '+':
                res = soma(n1, n2);
                return res;
            case '-':
                res = subtracao(n1, n2);
                return res;
            case '*':
                res = multiplicacao(n1, n2);
                return res;
            default:
                res = divisao(n1, n2);
                return res;
        }
    }

    static double soma(int num1, int num2) {
        double res;
        res = num1 + num2;
        return res;
    }

    static double subtracao(int num1, int num2) {
        double res;
        res = num1 - num2;
        return res;
    }

    static double multiplicacao(int num1, int num2) {
        double res;
        res = num1 * num2;
        return res;
    }

    static double divisao(int num1, int num2) {
        double res;
        if (num2 != 0) {
            res = num1 / num2;
            return res;
        } else {
            System.out.println("Impossible.");
            return 0.0;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

next给出一个字符串,你想要一个char。你可以试试

char oper = entrada.next().charAt(0);

答案 1 :(得分:1)

public String next()

next()正在返回一个String对象,如果你想存储一个角色,你需要:

entrada.next().charAt(0);

将来发布错误时,请发布实际错误。