java - if, else if 循环问题
问题描述
所以我刚刚完成了我的第一堂计算机编程课,但我的主要方法有问题。我有2节课。第一个类是 homeClass.java,另一个类是 homeInventory.java。我只是要向你展示我的一些 homeInventory.java 类,除非你更聪明的人觉得让我的其他类是谨慎的。基本上,我的 else if 语句有问题。该程序使用 if 语句运行,但不会完全运行其他选项(else if)。我一定遗漏了一些非常明显的东西,但我只会看看你要说什么。提前致谢!
public static void main(String[] args) {
ArrayList<homeClass> homes = new ArrayList<>();
Scanner scnr = new Scanner(System.in);
int i = 0;
int j = 0;
String option = "";
String answer = "";
String statusAnswer = "";
do {
System.out.println("Menu:");
System.out.println("1. Add a new home.");
System.out.println("2. Remove a home.");
System.out.println("3. Update home sale status.");
System.out.println("4. Exit");
System.out.print("Option chosen: ");
try {
while(true) {
if(scnr.hasNext()) {
option = scnr.next();
break;
}
}
}
catch (NoSuchElementException NSEE) {
continue;
}
catch (Exception excpt) {
excpt.printStackTrace();
System.out.print("Error, non-integer");
break;
}
try {
if(option.equals("1")) {
homes.add(addHome(scnr));
System.out.println("Home added.");
homes.get(i).getListing();
break;
}
else if (option.equals("2")) {
for(j = 0; j < homes.size(); ++j) {
homes.get(i).getListing();
System.out.print("Remove this listing? Y or N: ");
answer = scnr.next();
if (answer.equalsIgnoreCase("Y")) {
homes.get(i).removeListing();
System.out.println("Home removed.");
}
else if (!answer.equalsIgnoreCase("Y")) {
System.out.println("Home not removed. Choose next option.");
}
}
break;
}
else if (option.equals("3")) {
for(j = 0; j < homes.size(); ++j) {
homes.get(i).getListing();
System.out.print("Do you want to change the sale status? Y or N: ");
answer = scnr.next();
if (answer.equalsIgnoreCase("Y")) {
System.out.println("Enter home sale status: ");
statusAnswer = scnr.next();
homes.get(i).setSaleStatus(statusAnswer);
homes.get(i).getListing();
}
}
break;
}
}
catch (Exception excpt) {
excpt.printStackTrace();
System.out.println("Error, option failed.");
}
} while(!option.equals("4"));
System.out.print("Do you want the home information stored in a file? Y or N: ");
answer = scnr.next();
String outputFileName = "C:\\Temporary\\Home.txt";
for (j = 0; j < homes.size(); ++j) {
String listing = homes.get(i).getListing();
if (answer.equalsIgnoreCase("Y")) {
try {
printToFile(listing, outputFileName);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("File printed to: " + outputFileName);
}
else {
System.out.println("File not printed.");
}
}
scnr.close();
return;
}
}
解决方案
推荐阅读
- android - Android 错误 - Gradle 项目同步失败
- google-sheets - 在 Google 表格中使用条件格式突出显示
- html - 带有媒体查询的设备方向
- azure-devops - 如何将已关闭项目分配给过去的 Sprint
- python - 使用 keras 训练时出现奇怪的结果
- spring-boot - 在 spring 响应式项目中集成 camunda webapp
- javascript - Javascript 无效的日期字符串
- java - 无法反序列化“java.util.ArrayList”的实例
- java - 如果管道崩溃,如何将消息发送到队列
- javascript - 确保用户在“正确的”网页上?