Java SE do while loop issues

久未见 提交于 2019-12-02 12:37:24

You're trying to access variables outside the scope they're declared in. You have to declare the variables outside the do so you can access them in the 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);

But I see now that Room is also declared with the wrong scope. You have to declare it before the loop if you want to access it afterwards. So a simpler solution might be:

    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);

Incidentally, it doesn't seem right that you're looping until all dimensions are 0. I suspect you mean to check == 0.

You have to declare the variables roomLength, roomWidth and roomHeight in front of the do-while loop.

Like this:

double roomLength = 0;
double roomWidth = 0;
double roomHeight = 0;
do { 
    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);

The problem is the scope of your variables. roomLength, roomWidth and roomHeight are only visible inside the do-block. But the statements inside the while are outside of the do-block. Thats why the variables could not be found.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!