0
private static void square() {
    System.out.println("Would you like to find Area or Perimeter?");
    String pOrA=sc.next();
    if (pOrA.equals("Perimeter"));
    {
        System.out.println("What is the side length?");
        Double sSide=sc.nextDouble();
        double p = sSide *4;
        System.out.print("The perimeter is " + p);
    }
            //this is where the error is happening
    else if (pOrA.equals("Area"));
    {
        System.out.println("What is the side length?");
        Double sSide2=sc.nextDouble();
        double a = sSide2 * sSide2;
        System.out.print("The Perimeter is " + a);
    }

    }   

在 Eclipse 中,else-if 块出现错误,指出“令牌'else' 上的语法错误,删除此令牌”。老实说,我不知道为什么它不起作用。else-if 语句在自定义方法中的工作方式是否不同,因为它在 main 方法的早期工作正常。

4

4 回答 4

5

您的问题是由第一个后的附加分号引起的if

if (pOrA.equals("Perimeter"));
{
    System.out.println("What is the side length?");
    Double sSide=sc.nextDouble();
    double p = sSide *4;
    System.out.print("The perimeter is " + p);
}

这实际上相当于:

if (pOrA.equals("Perimeter"))
{
   // empty block
}

// scope block
{
    System.out.println("What is the side length?");
    Double sSide=sc.nextDouble();
    double p = sSide *4;
    System.out.print("The perimeter is " + p);
}

只需删除多余的分号。

于 2013-05-27T04:59:59.050 回答
1

删除;after theifelse语句,尤其是;after theif导致错误。

此外,;可能不需要后面的语句,编译错误的原因是后面的块语句if(..);,而是“拆分”了 if..else。

这是没有块的合法代码:

if (condition);
else; 
{}

但是如果我们添加另一个块,这是另一个“语句”,则会发生编译错误,因此现在else看起来与 any 无关if

if (condition);
{}                 // <- now the compiler exepects that there is no else for that if
else;              // <- and that else here doesn't have a preceeding if anymore
{}
于 2013-05-27T04:59:56.920 回答
0

删除if和 之后的分号else

于 2013-05-27T05:00:27.357 回答
0

由于您的代码中的第一行:

    if (false);

你不必;像下面这样:

private static void square() {
System.out.println("Would you like to find Area or Perimeter?");
String pOrA=sc.next();
if (pOrA.equals("Perimeter"))
{
    System.out.println("What is the side length?");
    Double sSide=sc.nextDouble();
    double p = sSide *4;
    System.out.print("The perimeter is " + p);
}
        //this is where the error is happening
else if (pOrA.equals("Area"))
{
    System.out.println("What is the side length?");
    Double sSide2=sc.nextDouble();
    double a = sSide2 * sSide2;
    System.out.print("The Perimeter is " + a);
}

} 
于 2013-05-27T05:02:53.920 回答