我的Java应用程序在编译代码时遇到问题,它说它找不到符号 roomLength 。应用程序应该执行的操作是提示用户输入房间名称,然后如果该房间名称为“退出”,则必须关闭该程序。否则会提示输入房间的长度,宽度和高度。如果这些尺寸中的任何一个等于或小于零,它将再次提示输入尺寸。
class Room { private String name; private double length; private double width; private double height; public Room(String r, double l, double w, double h) { name = r; length = l; width = w; height = h; } public String getName() { return name; } public double getLength() { return length; } public double getWidth() { return width; } public double getHeight() { return height; } public double getArea() { double area = length*width; return area; } public double getVolume() { double volume = length*width*height; return volume; } public void setName(String s) { name = s; } }
这是我的主要方法。
import java.util.Scanner; class TestRoom { public static void main(String [] args) { Scanner userInput = new Scanner(System.in); System.out.println("Please enter the name of room"); String roomName = userInput.next(); if(roomName.equals("quit")) { userInput.close(); } else { do { Scanner dimensionsInput = new Scanner(System.in); System.out.print("Please enter the dimensions of the room, length, width and height accordingly"); double roomLength = dimensionsInput.nextDouble(); double roomWidth = dimensionsInput.nextDouble(); double roomHeight = dimensionsInput.nextDouble(); Room r = new Room(roomName, roomLength, roomWidth, roomHeight); } while (roomLength > 0 || roomWidth > 0 || roomHeight > 0); System.out.println("The name of room: " + r.getName() + " Dimensions: L= " + r.getLength() + "X " + "W= " + r.getWidth() + "X " + "H= " + r.getHeight()); System.out.println("Area of room= " + r.getArea()); System.out.println("Volume of room= " + r.getVolume()); } } }
提前致谢!;)
还有一个几乎与此问题类似的问题,只是它应该循环回到第一个提示,允许用户输入另一个房间的名称和尺寸。
干杯!
您正在尝试访问在声明范围之外的变量。您必须在声明外部声明变量,do以便可以在中访问它们while:
do
while
double roomLength; double roomWidth; double roomHeight; do { Scanner dimensionsInput = new Scanner(System.in); System.out.print("Please enter the dimensions of the room, length, width and height accordingly"); roomLength = dimensionsInput.nextDouble(); roomWidth = dimensionsInput.nextDouble(); roomHeight = dimensionsInput.nextDouble(); Room r = new Room(roomName, roomLength, roomWidth, roomHeight); } while (roomLength > 0 || roomWidth > 0 || roomHeight > 0);
但是我现在看到这Room也是用错误的范围声明的。如果要随后访问它,则必须在循环之前声明它。因此,一个更简单的解决方案可能是:
Room
Room r; do { Scanner dimensionsInput = new Scanner(System.in); System.out.print("Please enter the dimensions of the room, length, width and height accordingly"); double roomLength = dimensionsInput.nextDouble(); double roomWidth = dimensionsInput.nextDouble(); double roomHeight = dimensionsInput.nextDouble(); r = new Room(roomName, roomLength, roomWidth, roomHeight); } while (r.getLength() > 0 || r.getWidth() > 0 || r.getHeight() > 0);
顺便说一句,直到所有尺寸都为0,才循环播放似乎不对== 0。我怀疑您要检查。
== 0