0

I have searched but didn't find anything so apologies if I didn't search on the correct term I'm a nooby.

I have some code I've written which scans in some books details which works great on lap 1 of the for loop.. On the 2nd lap however the :-

        System.out.print("Enter the books title: ");
        String title = sc.nextLine();

Part of the code is skipped for some reason sending me straight to the next lines asking for the cost which causes an exception.

For loop code:-

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    DB[] books = new DB[2];

    for (int i=0; i < books.length; i++) {
        System.out.print("Enter the books title: ");
        String title = sc.nextLine();

        System.out.print("Enter the cost of the book £");
        float cost = sc.nextFloat();

        System.out.print("How many copies of this book in stock? ");
        int stock = sc.nextInt();

        System.out.print("Is ths book a hardback (Y or N)? ");
        String cover = sc.next();

        boolean type = false;
        if (cover.charAt(0) == 'Y' || cover.charAt(0) == 'y') 
            type = true;

        DB book = new DB();

        book.name = title;
        book.price = cost;
        book.inv = stock;
        book.hardback = type;

        books[i] = book;

    }//end for loop

    printStock(books);


sc.close(); 
}//end main

It's like the nextLine(); is being skipped because it already contains a value. I've tried setting 'title' to "nul" at the beginning of the loop but it made no difference.

Thanks in advance.

  • 1
    Tag the language. – underscore_d Nov 03 '17 at 11:35
  • Looks like Java, just asking, why aren't you using List instead of array? Anyhow, https://stackoverflow.com/a/22458766/5529540 next() places the cursor in the same line after reading the input. – Janno Nov 03 '17 at 11:38
  • Hi, thanks for your reply.. I have read all that but it doesn't explain why the code is skipping the "String title = sc.nextLine();" code after the first loop. I can't use next(); as I need to be able to read spaces to be printed out later. – Dave Graham Nov 03 '17 at 13:19
  • Maybe the cause of your problem is explained here https://stackoverflow.com/q/13102045/8587776 – Digvijaysinh Gohil Nov 03 '17 at 18:04

0 Answers0