如果选项有效,否则无效

时间:2013-12-20 00:11:36

标签: java

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

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

已解决:选择== 1应为2。

我是否还可以添加这个问题,最好将插入的数据放入数组中,如果是这样,我应该在主类,超类或Sub类中声明数组

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());
            }

        }

3 个答案:

答案 0 :(得分:2)

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

如果choice等于1,您就永远无法进入其他部分。另一方面,如果你在其他方面,choice无法匹配1,因为你知道它不等于1,因为你进入了否则部分原因是第一个条件是假的。

答案 1 :(得分:1)

您的ifelse if都使用相同的值进行比较。您应该为值或枚举定义常量。然后,您可以按如下方式编写代码:

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
if (choice == 1) { // Use constant or enum here
    book1 = new fiction(title,author);
    System.out.println(book1.toString());
}
else if (choice == 2) { // Use constant or enum here
   book1 = new nonfiction(title,author);
   System.out.println(book1.toString());
}

答案 2 :(得分:0)

您在if。

的两个部分中检查choice == 1