gpt4 book ai didi

Java - 无法执行一系列 1-7 中的最后一个 if 语句

转载 作者:行者123 更新时间:2023-12-01 18:35:45 26 4
gpt4 key购买 nike

“选择”变量用于调用不同的方法并执行不同的代码块。一切工作正常,除了当我想退出程序时(即当选择== 7时)。有谁知道这是为什么吗?

public class HW5Main {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean breakRequest = false;

while(breakRequest == false){
System.out.println("\nWelcome to JVHS, what would you like to do?");
System.out.println("1. Admit a new dog (description unknown)");
System.out.println("2. Admit a new dog (description known)");
System.out.println("3. Display information about a particular dog");
System.out.println("4. Adopt a dog");
System.out.println("5. Euthanize a dog");
System.out.println("6. Display information about the JVHS");
System.out.println("7. Exit");
int selection = scanner.nextInt();
System.out.println("\nYour selection is "+ selection);

HW5Dog dogObject = new HW5Dog();

if(selection == 1)
dogObject.addDog();

if(selection == 2)
dogObject.addDog2();

if(selection == 3){
dogObject.getAllDogs();
//Ask which Dog you want and get its info
System.out.println("Please enter the ID number of the dog you wish to display:");
if(scanner.hasNextInt()){
int dogID = scanner.nextInt();
dogObject.getDog(dogID);
}
else
System.out.println("ERROR - INVALID INPUT: EXPECTING INTERGER, TRY AGAIN");
}

if(selection == 4){
dogObject.getAllDogs();
//Ask which Dog you want and get its info
System.out.println("Please enter the ID number of the dog you wish to adopt:");
if(scanner.hasNextInt()){
int dogID = scanner.nextInt();
dogObject.adopt(dogID);
}
}

if(selection == 5){
dogObject.getAllDogs();
//Ask which Dog you want and get its info
System.out.println("Please enter the ID number of the dog you wish to euthanize:");
if(scanner.hasNextInt()){
int dogID = scanner.nextInt();
dogObject.euth(dogID);
}

if(selection == 6){
dogObject.getJVHS();
}

if(selection == 7){
System.out.println("Goodbye");
scanner.close();
breakRequest = true;
}

}
}
}
}

最佳答案

问题出在上面的选择 block 中:

if(selection == 5){
dogObject.getAllDogs();
//Ask which Dog you want and get its info
System.out.println("Please enter the ID number of the dog you wish to euthanize:");
if(scanner.hasNextInt()){
int dogID = scanner.nextInt();
dogObject.euth(dogID);
}

您没有关闭第二个 if 语句中的大括号。它应该是这样的:

if(selection == 5){
dogObject.getAllDogs();
//Ask which Dog you want and get its info
System.out.println("Please enter the ID number of the dog you wish to euthanize:");
if(scanner.hasNextInt()) {
int dogID = scanner.nextInt();
dogObject.euth(dogID);
}
}

正如一些评论中提到的,您应该坚持使用清晰一致的缩进样式,以便将来更容易发现此问题。

关于Java - 无法执行一系列 1-7 中的最后一个 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22107291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com