笨拙的Java Calc无法编译

时间:2018-05-13 12:24:22

标签: java

我是编程的新手,因此这段代码让我不知所措,因为它无法编译。 Net Beans建议添加return 0,然后代码编译成功。但是,打印到控制台Anything else to calculate?后的部件无法正确处理输入,无论输入数据如何都显示Please, enter a valid answer

package calc;
import java.util.Scanner;
public class Calc {
    public static void main(String[] args){
        Calculator();
    }

    static double sum (double val1, double val2){
        return val1 + val2;
    }

    static double substract (double val1, double val2) {
        return val1 - val2;
    }

    static double multiply (double val1, double val2) {
        return val1 * val2;
    }

    static double divide (double val1, double val2) {
        return val1 / val2;
    }

    public static double Calculator(){
        Scanner reader = new Scanner(System.in);
        System.out.println(" Enter the first number, please");
        double x = reader.nextDouble();
        System.out.println("Enter the second number, please");
        double y = reader.nextDouble();
        System.out.println("Enter desired operation, please");
        char z = reader.next().charAt(0);
        switch(z)
        {
        case '+':
            double a = sum(x,y);
            System.out.println(a);
            break;
        case '-':
            double b = substract(x,y);
            System.out.println(b);
            break;
        case '*':
            double c = multiply(x,y);
            System.out.println(c);
            break;
        case '/':
            double d = divide (x,y);
            System.out.println(d);
            break;
    }
    System.out.println("Anything else to calculate?");
    Scanner reader2 = new Scanner(System.in);
    String Answer = reader2.nextLine();
    if (Answer == "yes") {
        Calculator();
    } else if (Answer == "no") {
        System.out.println("Thank you for using our Calculator app");
    } else {
        System.out.println("Please, enter a valid answer");
    }
}

2 个答案:

答案 0 :(得分:0)

您不使用==比较字符串,而是使用equals(),或者在这种情况下更好equalsIgnoreCase

if (Answer.equalsIgnoreCase("yes")) {
    Calculator();
} else if (Answer.equalsIgnoreCase("no")) {
    System.out.println("Thank you for using our Calculator app");
} 

答案 1 :(得分:-1)

亲爱的,因为函数Calculator有一个双返回类型,所以它应该如何返回一个double值。但是根据你的代码,你没有返回任何东西 并简单地在控制台中打印结果,因此无需定义函数的返回类型以将其标记为void。我希望这会让您理解这个概念。