ooodddbbb
ooodddbbb

Reputation: 121

compiler error: array required, but String found

Getting a error: array required, but String found. I checked and rechecked, yet couldn't find anything wrong with my code. What's going wrong? I have been introduced to java a year ago, but only when i started working on a project to develop a library management system do I realise the serious deficiencies in my knowledge.

import java.util.Scanner;

public class library{
book[] bk = new book[5];

public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    library mainObj = new library();

    mainObj.addBooks();
}

public void addBooks(){
    Scanner input = new Scanner(System.in);

    System.out.print("Book Name: ");
    String bk = input.nextLine();

    System.out.print("Author Name: ");
    String aun = input.nextLine();

    System.out.print("Id: ");
    String i = input.nextLine();

    bk[book.getTotalBookCount()] = new book(bk, aun, i);
}

}

class book{
String name;
String authorName;
String id;
static int totalBookCount = 0;

book(String bkn, String aun, String i){
    name = bkn;
    authorName = aun;
    id = i;
    totalBookCount++;

    System.out.println("Book Added!! ");
}

}

Upvotes: 0

Views: 215

Answers (3)

Ashish Ani
Ashish Ani

Reputation: 332

You have used bk twice for two different types i.e. one for book array and another for string. And in these type of collisions, local type gets priority so,

 bk[.....] = ......;
 ^^^^^   
Here, `bk` will be considered as string, but we are using `[]` brackets with it, hence the error: array required, string found.

Upvotes: 1

Furqan Aziz
Furqan Aziz

Reputation: 1104

You are using bk variable twice. Once at top while declaring array book[] bk = new book[5]; and once in addBooks function String bk = input.nextLine(); at third line.

Upvotes: 1

Sarvadi
Sarvadi

Reputation: 560

String bk = input.nextLine();

You're shadowing book[] bk with that variable. Either change the name of one of them, or use this instead.

this.bk[book.getTotalBookCount()] = new book(bk, aun, i);

Upvotes: 2

Related Questions