【问题标题】:Cannot convert from int[] to int? [duplicate]无法从 int[] 转换为 int? [复制]
【发布时间】:2015-12-09 15:42:15
【问题描述】:

我是一般编程新手,我一直在尝试用 java 为我的 comp sci 课程构建一个系统,但在 eclipse 中出现错误“无法从 int[] 转换为 int”。

public static ArrayList<Book> CreateBooksArrayList(){
    int[] id = {1,2,3,4,5};
    String[] bookTitle = {"book1", "book2", "book3", "book4", "book5"};
    String[] authorName = {"author1", "author2", "author3", "author4", "author5"};
    double[] bookReleaseYear = {123,456,789,987,654};
    int[] numOnLoan = {1,2,2,3,4};
    int[] numInStock = {5,5,5,5,5};


    int bID = -1;
    String bTitle = null;
    String aName = null;
    double bRelease = -1;
    int nLoan = -1;
    int nStock = -1;

    ArrayList<Book> Books = new ArrayList<Book>();
    for (int i = 0; i<6; i++){
        bID = id[i];
        bTitle = bookTitle[i];
        aName = authorName[i];
        bRelease = bookReleaseYear[i];
        nLoan = numOnLoan;
        nStock = numInStock;
        Books.add(new Book(bID, bTitle, aName, bRelease, nLoan, nStock));

我已尝试寻找答案,但我似乎无法找到与此确切问题相关的任何链接。提前感谢您的帮助!

【问题讨论】:

  • 仅根据消息,您认为错误意味着什么?
  • 您在设置nLoannStock 时忘记了[i] 部分。应该是nLoan = numOnLoan[i];
  • 我认为它似乎是与使用 int 数组和 int 相关的问题,但我想不出如何解决它
  • 谢谢 Gonzo,我试试看 :)
  • 非常感谢!这么愚蠢的错误

标签: java arrays arraylist int


【解决方案1】:

您忘记了 for 循环中 numOnLoannumInStock[i] 部分。将它们都更改为包含[i]

nLoan = numOnLoan[i];
nStock = numInStock[i];

【讨论】:

    【解决方案2】:

    替换

    nLoan = numOnLoan;
    nStock = numInStock;
    

    与:

    nLoan = numOnLoan[i];
    nStock = numInStock[i];
    

    【讨论】:

    • 谢谢伯杰!我不敢相信我没有看到它。
    【解决方案3】:

    尝试更改这些行:

        nLoan = numOnLoan;
        nStock = numInStock;
    

    使用这些您忘记了循环的索引i 以从数组中检索值:

        nLoan = numOnLoan[i];
        nStock = numInStock[i];
    

    【讨论】:

    • 谢谢 Abdelhak,只需将 [i] 添加到 numOnLoan 和 numInStock 即可修复它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-20
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    相关资源
    最近更新 更多