Reputation: 71
i have a method i am working on, its part of a larger program but i think the code i posted will be enough.
When i select option 1 in my menu, it works as it should, but when i select option 2 , it just ends the program. can anybody spot the issue?
Resolved : the choice == 1 should be 2.
Can i also add to this question, would it be best to put the in putted data into an array, if so, should i declare the array in the main class,superclass or the Sub 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());
}
}
Upvotes: 4
Views: 86
Reputation: 41117
Your if
and the else if
both uses the same value to compare. You should define a constant for the values or enum. You can then write your code as follows:
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());
}
Upvotes: 1
Reputation: 68907
You wrote: if (x == 1) { } else if (x == 1) {}
If choice
is equal to 1
, you can never get into the the else part. From the other side, if you are in the else body, choice
can't match 1
, because you know it is not equal to 1
, because of the fact you got in the else part due to the fact that the first condition was false.
Upvotes: 2