需要帮助Java简单规则形状面积计算器和if语句吗
我试图完成一个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);
}
}
在此方面的任何帮助都将不胜感激
# 1 楼答案
我认为因为
double calculation
是在if语句中声明的,所以不能在else if
中使用它,因为它只存在于第一个if语句中。在if
和else if
之前声明它,以便能够在所有语句中使用它