-3

I'm trying to make a simple bookstore program where people can browse the books and buy some if they want. First they'll choose a genre then choose a title before checking out. If they want to buy more, they'll be sent back to the genre selection.

package finalOOP1;

import java.util.Scanner;

public class main {
    //i wanna make a bookstore that sells novels from all genre
    public static void main(String[]args)
    {
        Scanner scan = new Scanner(System.in);
        horror h1 = new horror();

        System.out.println("Pick a genre:");
        System.out.println("Horror");
        System.out.println("Adventure");
        System.out.println("Fantasy");
        String genre = scan.next();

        if (genre=="Horror")
        {
            h1.titles();
        }

    }
}

import java.util.Scanner;

public class horror {

     static Scanner scan = new Scanner(System.in);

    public static void titles()
    {
        System.out.println("Pick a book number.");
        System.out.println("1.1984");
        System.out.println("2.Goosebumps");
        System.out.println("3.Dracula");
        System.out.println("4.Go back to genre selection");
        int choose = scan.nextInt();

        if (choose == 1)
        {
            System.out.println("You chose 1984.");
        } else if (choose == 2)
        {
            System.out.println("You chose Goosebumps.");
        } else if (choose == 3)
        {
            System.out.println("You chose Dracula.");
        } else
        {
            main.main(null); //calling the main method from main.java
        }
    }
}

I haven't made the other genres coz I just wanna try one first, but when I run the main.java, I input Horror, it immediately terminate itself. It didn't show the book titles. I'm wondering if I did something wrong?

I'm new to Java, so I don't really know how this works. Isn't horror.java supposed to work like a function in c++?

Novelcie
  • 56
  • 7
  • There are a lot of other issues, but what you are bothering with right now is `if (genre=="Horror")`. To compare Strings you should use following construction `if ("Horror".equals(genre))` – Damian Lesniak Apr 08 '20 at 09:16

1 Answers1

2

Replace

if (genre=="Horror")

with

if (genre.equalsIgnoreCase("Horror"))

String in java is an object. "==" checks if both the objects are equal, not the characters are same. Also, conventionally, java class names should start with capital letter.

There are some more issues, We don't do this in java main.main(null); //calling the main method from main.java

Nandu Raj
  • 2,072
  • 9
  • 20