即使在开始进行表面积计算之前,双宽度也无法与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");
答案 0 :(得分:2)
Java具有block scope
在块{}
中声明的任何变量都无法在该块外部访问。您可以在范围之外使用变量,但不能以其他方式使用。您需要做的是在范围之外声明变量。您可能还想向用户抛出异常。
double width;
if(in.hasNextDouble()){
width = in.nextDouble();
System.out.println("Width/Height: " + width);
} else {
throw new IllegalArgumentException("Please enter only numbers");
}
答案 1 :(得分:0)
您在此width
语句的块内声明了if
:
if(in.hasNextDouble()){
double width = in.nextDouble();
System.out.println("Width/Height: " + width);
}
因此,此块是width
的范围,在它之外不可见。
你应该怎么做?
这样声明:
double width;
if(in.hasNextDouble()){
width = in.nextDouble();
System.out.println("Width/Height: " + width);
}
现在width
对main()
的其余部分可见,尽管它可能尚未初始化。所以也许这更安全:
double width = 0.0;