If the option works, but if not,

I have a method I'm working on, part of a larger program, but I think that the code I posted will suffice.

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 anyone identify the problem?

Solved: choice == 1 should be 2.

Can I also add to this question, it would be better to put the placed data in an array, if so, I should declare the array in the main class, superclass or subclass

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

        }
+4
source share
3 answers

if else 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());
}
+1

: if (x == 1) { } else if (x == 1) {}

choice 1, else. , else, choice 1, , 1, - , - .

+2

You check choice == 1in both parts of the if.

0
source

All Articles