1

// Problem Statement: WAP to create a class Library and use methods addBook and showAvailableBooks to store and show books in the library. // I am new to java and I am getting an issue after running the below program. I am not able to fill the first index place of the array addBook.

package com.company;
import java.util.Scanner;

class Library{
    Scanner sc = new Scanner(System.in);
    int numOfBooks;
    String[] addBook;

    Library(){
        System.out.print("Enter the number of books you want to add to the library: ");
        numOfBooks = sc.nextInt();
        this.addBook = new String[numOfBooks]; //New String called "addBook" is being created.
    }

    public String[]addBook(){
        for(int i=0; i<numOfBooks; i++){
            int j = i+1;
            System.out.print("Add Book "+j+" Name: ");
            this.addBook[i] = sc.nextLine();
        }
        return addBook;
    }

    public void showAvailableBooks(){
        for(int i=0; i<numOfBooks; i++){
            System.out.println(addBook[i]);
        }
    }
}
public class CWH_51_Exercise_4 {
    public static void main(String[] args) {
        Library l = new Library();
        l.addBook();
        l.showAvailableBooks();
    
    }
}

2 Answers2

0

That it's probably caused by sc.nextInt() in your Library contructor. It reads the int given, but it does not read the '\n' character (origined when you press enter).

When nextLine() is called for first time, it reads that missing '\n'.

Try calling nextLine() after every nextInt().

    System.out.print("Enter the number of books you want to add to the library: ");
    numOfBooks = sc.nextInt();
    sc.nextLine(); // Consume '\n'
    this.addBook = new String[numOfBooks];
0

i suggest you avoid using sc.nextInt() and use this instead:

        numOfBooks = Integer.parseInt(sc.nextLine());

See this question for the explanation

Piaget Hadzizi
  • 408
  • 2
  • 10