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



我正试图完成一个java项目,使一个程序,需要输入一个规则的形状之间3 & &;然后取边长,计算并打印。这是我第一次使用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之前声明它,以便能够在所有语句中使用它。

最新更新