简体   繁体   中英

Java console input doesn't work as intended

So I wrote a programm that prints information about a book if you type in the title and it works perfectly fine if you type in the title directly as a string like that:

bs.getBook("book");

But I want it to read the title from a console input like that:

String inputResult = System.console().readLine();
bs.getBook(inputResult);

But it just doesn't work for some reason. If I just try to print the input, it prints the string that I typed in so it should actually work with getBook too but it doesn't. Did I miss something?

That's the getBook method:

public void getBook(String title) {
        for (int i = 0; i < books.length; i++) {
            if (books[i].title == title) {
                System.out.println(books[i]);
        } else {
            System.out.println("0");
            }
        }
    }

So here is an example: if I'm typing in the book title like this:

bs.getBook("book");

it prints out the information in the console as it should do like that:

Book(book, 8494030, 22.1)

but if I try to type in the title in the command line using:

String inputResult = System.console().readLine();
bs.getBook(inputResult);

it doesn't work. If I try to print what I typed in though like that:

System.out.println(inputResult);

It prints what I typed in so why doesn't it work properly in the getBook method?

I dont't think your scanner/reader is the problem here. In your getBook method try to compare the title with equals

if (books[i].title.equals(title)) {

I assume your .title method returns a String with the title of the book it would be easier to understand if you would call it getTitle


And you can try to use a buffered reader

    InputStream is = System.in;
    BufferedReader in = new BufferedReader(new InputStreamReader(is));

    System.out.println("Enter Book Title: ");
    String input = "";

    try {
        input = in.readLine();
        System.out.println("Your Input: " + input);

        is.close();
        in.close();
    } catch (IOException e) {
        System.out.println("Error reading input");
    }

Try to get the value using Scanner from command line

System.out.println("Enter your book name: ");
Scanner scanner = new Scanner(System.in);
String bookName= scanner.nextLine();
System.out.println("Your book name is " + bookName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM