1

I am encountering a problem I cannot figure out. I am using a single Scanner object and am passing it around (painfully I learned that multiple Scanner objects on the same stream cause issues https://www.securecoding.cert.org/confluence/display/java/FIO06-J.+Do+not+create+multiple+buffered+wrappers+on+a+single+byte+or+character+stream). The Scanner works fine, and collects information from the user before and after this section of the code. However in this section of the code, it does not stop to get user input.

Can you help explain why the code below is broken?

//class A
Scanner in; //global value

String bookName = "";//global value

in = new Scanner(System.in); //initialized in class A constructor

//inside main of class A

System.out.println("before: " + a.bookName);
a.bookName = c.getBookName(a.in, a.bookName);
System.out.println("after: " + a.bookName);

//method in class C to get the data from the user via terminal

 public String getBookName(Scanner in, String bookName) 
 {

        System.out.println("enter name as appears in the database!");

        System.out.println("current value: >"+ bookName + "<");
        bookName = in.nextLine();

        System.out.println("userInput: >" + bookName + "<");

        return bookName;
    }

the output (code in question has reduced user prompt than in image below): enter image description here

when I run this code, the program runs through the getBookName method without stopping to get any user info. Why is the Scanner object not collecting the user input? and how do I modify the defect to collect a string with spaces (ex: "you are awesome for helping... Thanks!")?

I tried in.reset(), not initializing the global bookName variable, using next() instead of nextLine(), using nextLine() in a custom class to make sure I understand it, and a bunch of other stuff and I just don't get why this code doesn't work.

Willem Van Onsem
  • 321,217
  • 26
  • 295
  • 405
Mike
  • 311
  • 3
  • 15

0 Answers0