2013-12-20 37 views
4

我有一个方法,我正在工作,它的一部分较大的程序,但我认为我发布的代码就足够了。如果选项的作品,但如果不是

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

解决的问题:选择== 1应该是2

可我也加入到了这个问题,这将是最好把推杆中的数据到一个数组,如果是的话,我应该在声明数组主类,超类或子类

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

     } 
+1

也许用'否则,如果(选择== 2){'... – Reimeus

+0

这么简单的事,好点。谢谢。 – user2854120

回答

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

你的,如果两个部分检查choice == 1

2

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

如果choice等于1,你永远不能进入else部分。从另一方面来说,如果你在其他方面,choice不能匹配1,因为你知道它不等于1,因为你得到其他部分的事实,因为第一个条件是错误的。

相关问题