双宽度无法与 int 墙一起解析,即使在我开始表面积计算之前,它已编译。
import java.util.Scanner;
public class Assignment_3_4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Customer Name
System.out.println("Enter your First Name");
String Firstn = in.next();
System.out.println("Enter your Last Name");
String Lastn = in.next();
System.out.println("Valued Customer Name: " + Firstn + " " + Lastn);
//Wall Measurements
System.out.println("Enter the Width");
if(in.hasNextDouble()){
double width = in.nextDouble();
System.out.println("Width/Height: " + width);
} else {
System.out.println("Please enter only numbers");
}
System.out.println("Enter number of walls");
if(in.hasNextInt()){
int walls = in.nextInt();
System.out.println("Number of Walls: " + walls);
} else {
System.out.println("Please enter only integers");
}
//Calculate Surface Area - Width Height and Length are all the same measurement
double SA = ((width * width) * walls);
System.out.println("Area to be Painted: " + SA + " square meters");
最佳答案
Java 有所谓的 block scope
在 block {}
内声明的任何变量都无法在 block 外部访问。您可以使用作用域之外的变量,但反之则不行。您需要做的是在范围之外声明变量。您可能还想向用户抛出异常。
double width;
if(in.hasNextDouble()){
width = in.nextDouble();
System.out.println("Width/Height: " + width);
} else {
throw new IllegalArgumentException("Please enter only numbers");
}
关于java - 已声明的变量无法解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54857774/