java - Try-Catch 与 do while 循环
问题描述
// 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 行结束)。起初,我试图让我的布尔值 I 是或否,而不是真或假。当我无法弄清楚时,我决定做一个 try-catch 来提示用户输入 true 或 false。发生了两件事。第 36 行中的第一个“inService”变量现在表示无法解析。所以我使用了 Eclipse 建议并为“inService”创建了一个字段。当我运行程序并到达那部分时,循环从未停止过,我不得不手动终止控制台。
我将不得不为房间实现一个try-catch,以确保用户不会输入诸如“three”而不是“3”之类的字符串。我打算使用相同的方法,但我无法让这个工作。
任何帮助或建议将不胜感激。
解决方案
您的循环永远不会停止的原因是您在 y=2 之后设置scan.nextBoolean()
,因此如果该方法抛出异常,则 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);
但是如果你scan.hasNextBoolean()
在while条件下使用会更好,这样你就可以避免使用try-catch
while (scan.hasNextBoolean()) {
System.out.print("In Service: ");
boolean inService = scan.nextBoolean();
}
推荐阅读
- javascript - 在 prime-ng 自动完成中突出显示搜索文本
- git - .bat git pull 与 PM2 一起挂起,但手动运行时运行良好
- firebase - Firebase Cloud Functions 是否可以在 Blaze 计划中接收来自外部服务器的 http 请求?
- kubernetes - 部署推出后如何知道 Kubernetes 服务何时准备就绪?
- nlp - 使用 Spacy 模型查找语言 fr、es、ru 的情态动词
- nlp - Flair NER Metrics 解释
- php - 如何在 PHP Plates 模板引擎上显示错误
- matlab - 如何将持久变量保存到 .mat 文件中?
- python - 在类分布之间切换
- python - 使用导入方法时获取调用模块名称 - python