简体   繁体   English

编译器错误:需要数组,但找到字符串

[英]compiler error: array required, but String found

Getting a error: array required, but String found. 出现错误:需要数组,但是找到了String。 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. 一年前,我被引入Java领域,但是只有当我开始从事开发图书馆管理系统的项目时,我才意识到我所学知识的严重不足。

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!! ");
}

}

String bk = input.nextLine(); 字符串bk = input.nextLine();

You're shadowing book[] bk with that variable. 您正在用该变量遮盖book[] bk Either change the name of one of them, or use this instead. 更改其中之一的名称,或改用此名称。

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

You are using bk variable twice. 您使用bk变量两次。 Once at top while declaring array book[] bk = new book[5]; 一次声明数组book[] bk = new book[5]; and once in addBooks function String bk = input.nextLine(); 然后在addBooks函数中输入 String bk = input.nextLine(); at third line. 在第三行。

You have used bk twice for two different types ie one for book array and another for string. 您对两种不同类型使用了bk两次,一种用于书本数组,另一种用于字符串。 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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