0

如何纠正线路错误

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;
        }
    }
}
4

2 回答 2

1

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

char oper = entrada.next().charAt(0);
于 2012-09-17T01:52:07.120 回答
1
public String next()

next()正在返回一个String对象,如果要存储一个字符,则需要:

entrada.next().charAt(0);

以后发布错误时,请发布实际错误。

于 2012-09-17T01:54:04.647 回答