-2
import java.util.Scanner;

public class Rpn_calculator
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);


        double ans = 0;
        double n = 0;
        double r = 0;
        String j;


        System.out.println();
        System.out.println();   
        System.out.print("Please enter a value for n  ");
        n = keyboard.nextDouble();  
        System.out.print("Please enter a value for r  ");
        r = keyboard.nextDouble();  
        System.out.println("Please choose one of these operands:+,-,*,nCr,/ to     continue, or q to quit ");
        j = keyboard.nextLine();    
        while (j != "q")
        {
            if(j == "+")
                ans = n + r;
            if(j == "-")
                ans = n - r;
            if(j == "*")
                ans = n * r;
            if(j == "/")
                ans = n / r;
            if(j == "nCr")
                ans = factorial(n + r -1) / (factorial(r)*factorial(n - 1));
            System.out.print(ans);

            System.out.print("Please enter a value for n  ");
            n = keyboard.nextDouble();  
            System.out.print("Please enter a value for r  ");
            r = keyboard.nextDouble();  
            System.out.print("Please choose one of these operands:+,-,*,nCr,/ to continue or q to quit ");
            j = keyboard.nextLine();    
        }   
    }
    public static double factorial(double x);
    {   
        double sum = 1;
        int i; 
        for (i = 0; i<= x; i++);
        sum = sum * i;

        return sum;
    }
} 

我正在尝试为此作业创建一个 RPN 计算器,我相信我拥有使它起作用所需的东西,但是我的阶乘函数存在语法错误。它说“缺少方法体”。

另外,我不明白为什么,当我编译它时,我的字符串输入请求被完全忽略 - 将程序锁定在while循环中。我希望我没有遗漏一些非常明显的东西。

4

1 回答 1

6

有几个分号不应该有:

public static double factorial(double x); // <-- This one
{   
    double sum = 1;
    int i; 
    for (i = 0; i<= x; i++); // <-- This one
    sum = sum * i;

    return sum;
}

当您将分号放在签名之后时,您没有方法主体,因此会出现错误。该for循环不会是编译器错误,但它将是一个空循环。

另外,我认为您需要使用String.equals比较 Java 中的字符串,而不是==运算符。

于 2013-01-17T03:00:39.797 回答