// Add a New Ship
public static void addShip() {
// complete this method
Scanner scan = new Scanner(System.in);
System.out.println("Enter new Ship name: "); // Ask for ship name
String shipName = scan.nextLine();
System.out.print("Balcony: "); // How many Balcony suites
int balcony = scan.nextInt();
System.out.print("Ocean View:"); // How many Ocean view suites
int oceanView = scan.nextInt();
System.out.print("Room Suite: ");
int roomSuite = scan.nextInt();
System.out.print("Room Interior: ");
int roomInterior = scan.nextInt();
**int y = 1;
do {
try {
System.out.print("In Service: ");
boolean inService = scan.nextBoolean(); // Ask if the ship is in service
y=2;
}
catch(Exception e) {
System.out.println("Please enter true if ship is in service.");
System.out.println("or");
System.out.print("False if ship is not in service");
}
} while (y==1);
scan.nextLine();
shipList.add(new Ship(shipName, balcony, oceanView, roomSuite, roomInterior, inService)); //this is the inService error I am referring to
}**
我遇到麻烦的地方是粗体(从第19行开始,以36结尾)。起初,我试图将布尔值设为是或否,而不是true或false。当我不知道该怎么做时,我决定进行一次尝试捕获以提示用户输入true或false。 发生了两件事。第36行的“ inService”变量现在说无法解决。因此,我使用了Eclipse建议,并为“ inService”创建了一个字段。当我运行程序并到达该部分时,循环从未停止,我不得不手动终止控制台。
我还必须对房间实施try-catch,以确保用户没有输入诸如“ 3”而不是“ 3”之类的字符串。我本打算使用相同的方法,但无法使该方法正常工作。
任何帮助或建议,将不胜感激。
答案 0 :(得分:1)
循环永不停止的原因是您在scan.nextBoolean()
之后设置y = 2,因此,如果该方法引发异常,则将跳过y = 2的行,它将直接到达catch块。因此,在这种情况下,您应该在catch块内设置y = 2使其起作用。
int y = 1;
do {
try {
System.out.print("In Service: ");
boolean inService = scan.nextBoolean();
} catch (Exception e) {
y = 2;
}
} while (y==1);
但是,最好在while条件下使用scan.hasNextBoolean()
,这样就可以避免使用try-catch
while (scan.hasNextBoolean()) {
System.out.print("In Service: ");
boolean inService = scan.nextBoolean();
}
答案 1 :(得分:0)
无论输入的是正确还是不正确的,您都需要处理扫描程序的行尾令牌,因此这意味着您应在尝试和捕获的结尾都用scan.nextLine()
吞下此令牌。块。例如:
Scanner scan = new Scanner(System.in);
boolean inputOk = false;
boolean inService = false;
do {
try {
System.out.print("In Service: ");
inService = scan.nextBoolean(); // Ask if the ship is in service
inputOk = true;
scan.nextLine(); // ***** add this here *****
} catch (Exception e) {
System.out.println("Error: bad input. Enter either true or false");
scan.nextLine(); // ***** add this here *****
}
} while (!inputOk);
System.out.println("inService: " + inService);
if (scan != null) {
scan.close();
}
还要注意,我使用了一个描述性的布尔变量来控制do-while循环,因为它避免了使用1和2的“幻数”,从而使代码具有自我注释性,并使逻辑更易于理解。