gpt4 book ai didi

java - 如果选项有效但否则如果不

转载 作者:搜寻专家 更新时间:2023-11-01 03:06:27 25 4
gpt4 key购买 nike

我有一个正在研究的方法,它是一个更大程序的一部分,但我认为我发布的代码就足够了。

当我在菜单中选择选项 1 时,它可以正常工作,但是当我选择选项 2 时,它只是结束程序。有人能发现问题吗?

解决:choice == 1应该是2

我还可以补充这个问题吗,最好将输入的数据放入一个数组中,如果是这样,我应该在主类、父类(super class)还是子类中声明数组

static void addBook(){
String title,author;
int choice;
boolean onLoan;
loanbook book1; // TESTING ONLY
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){

System.out.println("Please enter book title: ");
title = keyboard.nextLine();
title = keyboard.nextLine();
System.out.println("Please enter book author: ");
author = keyboard.nextLine();
onLoan = false; // not used yet
book1 = new fiction(title,author);
System.out.println(book1.toString());
}
else if (choice == 1) {
System.out.println("Please enter book title: ");
title = keyboard.nextLine();
title = keyboard.nextLine(); ;
System.out.println("Please enter book author: ");
author = keyboard.nextLine();
onLoan = false; // not used yet
book1 = new nonfiction(title,author);
System.out.println(book1.toString());
}

}

最佳答案

您写道:if (x == 1) { } else if (x == 1) {}

如果 choice 等于 1,您永远无法进入 else 部分。另一方面,如果你在 else 体中,choice 无法匹配 1,因为你知道它不等于 1 , 因为第一个条件为假,所以你进入了 else 部分。

关于java - 如果选项有效但否则如果不,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20694122/

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