需要帮助 - Java 带有 if 语句的简单规则形状面积计算器

Need Help - Java simple regular shape area calculator with if statement

我正在尝试完成一个 java 项目,制作一个程序,该程序接受 3 和 6 边之间的规则形状的输入,然后获取边的长度、计算和打印。这是我第一次使用 java,所以我有点不确定从第 25 行开始出现的错误,比如“'x' 无法解析为变量”。我想我的数学计算是正确的,所以这可能是一个简单的解决方法,但我已经尝试了一段时间,并求助于澄清。该任务的唯一规定是需要一个 if 语句 运行 代码实现给定边数的适当公式,并将结果存储在变量中。

目前完整的代码如下:

import java.util.Scanner;

public class RegularShapeArea {

    public static void main(String[] args) {
    
    //user input takes number of sides between 3 & 6 and stores in 'sides'
        
    System.out.println("How many sides does the shape have (between 3 and 6)? ");
    Scanner sidenum = new Scanner(System.in);
    double sides = sidenum.nextDouble();
    
    //if statement to determine user input is between 3 & 6 or presents and error message
    
    if((sides <3) || (sides >6)) { 
        System.out.println("The value entered was not between 3 & 6.");
    }
    //else statement runs user input for length of sides if it is within correct parameters and storees value in 'lengths'
    else {
        System.out.println("How long is each side? ");
        Scanner sidelength = new Scanner(System.in);
        double length = sidelength.nextDouble();
    }

    if (length == 3) {
        double calculation = (Math.sqrt(3)/4) * (length *length);
    }
    else if (length == 4) {
        calculation = (length * length);
    }
    else if (length == 5) {
        calculation = (Math.sqrt(5 * (5 + 2 * (Math.sqrt(5)))) * length * length) / 4;
    }
    else if (length == 6){
        calculation = ((3 * Math.sqrt(3) * (length * length)) / 2);
    }
    
    
    System.out.Println("The surface are of a shape with" + sides + "sides, each of length" + sidelength + "is " + calculation);
    }

}

如有任何帮助,我们将不胜感激。

我认为因为你的double calculation是在if语句中声明的,你不能在else if中使用它,因为它只存在于第一个if语句中。在 ifelse if 之前声明它以便能够在所有语句中使用它。