如何使用户结束此程序?

时间:2016-09-17 01:34:28

标签: java loops simulator

// ************************************************************
// ELEVATOR.java
//
// ELEVAOTR SIMULATION
// PROBLEM: NEED TO FIND A WAY TO AMKE IT SO THAT THE PROGRAM KEEPS RNNING AFTER USER INPUTS 
// THIER FIRST DESIRED FLOOR.
// ************************************************************
import java.util.*;


public class Elevator_Simulation {

    public static void main (String[] args) { 
        Person User = new Person();
        Floor floors = new Floor();
        floors.moveElevator(User.getDesiredFloor()); 

    }
}

class Elevator { //NEEDS SETTER & GETTER METHODS 
    private int mass=0;
    private int capcity=0; 
    private String name="";
    private String color="";
}

class Floor { 


    ArrayList<Object> floorLevel = new ArrayList<Object>();

    Elevator Lift = new Elevator();
    Person Man = new Person();

    Floor() { //Floors 0-9
        floorLevel.add(Lift); //0
        floorLevel.add(null); //1
        floorLevel.add(null); //2
        floorLevel.add(null); //3
        floorLevel.add(null); //4
        floorLevel.add(null); //5
        floorLevel.add(null); //6
        floorLevel.add(null); //7
        floorLevel.add(null); //8
        floorLevel.add(null); //9
        }
        System.out.println("Elevator is at Floor: " + floorLevel.indexOf(Lift)  );


    public void moveElevator (int chosenFloor) {

        if (chosenFloor > 9) {
            System.out.println("Woooooah Buddy! You can only choose 0-9!");
            return;
        }
        if (chosenFloor == floorLevel.indexOf(Lift)) {
            System.out.println("Bro you're already on that floor...");
        }

            while (floorLevel.indexOf(Lift)>chosenFloor) {
                Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)-1 ) );
                System.out.println(floorLevel.indexOf(Lift) );
            }
            while (floorLevel.indexOf(Lift)<chosenFloor) {
                Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)+1 ) );
                System.out.println(floorLevel.indexOf(Lift) );
            }   

    }
}

class Person { 
    Scanner scan = new Scanner(System.in);
    public int getDesiredFloor() {
        int desiredFloor = scan.nextInt();
        return desiredFloor;
    }
}

上面是一个电梯模拟器代码(在我尝试用GUI制作一个之前),除了明显的初学者缺陷之外,我唯一的问题是,我找不到一种方法来制作它以便一旦用户输入一层,程序就不会结束。我至少希望程序运行,直到用户用命令结束它。我想在某个地方使用while循环,但在哪里?请帮助并指出我应该在此代码中改进的任何内容。

1 个答案:

答案 0 :(得分:0)

您可以将while循环放在

行周围
floors.moveElevator(User.getDesiredFloor());

只需为表示退出的值添加输入检查。