簡體   English   中英

編譯器錯誤:需要數組,但找到字符串

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

出現錯誤:需要數組,但是找到了String。 我檢查並重新檢查,但找不到我的代碼有任何問題。 怎么了 一年前,我被引入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!! ");
}

}

字符串bk = input.nextLine();

您正在用該變量遮蓋book[] bk 更改其中之一的名稱,或改用此名稱。

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

您使用bk變量兩次。 一次聲明數組book[] bk = new book[5]; 然后在addBooks函數中輸入 String bk = input.nextLine(); 在第三行。

您對兩種不同類型使用了bk兩次,一種用於書本數組,另一種用於字符串。 在這些類型的沖突中,本地類型具有優先權,

 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