【问题标题】:Incompatible type error int[] to int不兼容的类型错误 int[] 到 int
【发布时间】:2015-04-22 02:05:19
【问题描述】:

我收到一个错误,类型不兼容:int[] 无法转换为 int。有人可以解释为什么会发生这种情况以及我需要做些什么来解决它吗? 谢谢您的帮助。这是我的代码:

public static String readFinalQuestionBank() throws Exception
    {   
        File textFile = new File("C:\\Users\\Joseph\\Documents\\School Files - NHCC\\CSci 2002\\FinalQuestionBank_JosephKraemer.txt");  //file location
        ArrayList<String> question;
        ArrayList<String> answer; 
        ArrayList<String> category;
        ArrayList<String> topic;


        int[] i = new int[0];
        String[] structure = {"OO Programming", "Generics", "Bags", "Complexity & Efficiency", "Stacks", "Recursion", "Sorts", "Queues",
                              "Lists", "Iterators", "Searching", "Associative Arrays/Hashing", "Trees/Heaps", "Graphs"};

        try
        {
            Scanner scan = new Scanner(textFile);                   //Scanner to import file

            while(scan.hasNextLine())                               //Iterator - while file has next line
            {
                String qBank = scan.nextLine();                     //Iterator next line
                String[] line = qBank.split("::");             //split data via double colon

                question[i]++ = line[0];    //error is here!!

                System.out.println(qBank);

            }
            scan.close();                  //close scanner

        }
        catch(FileNotFoundException e)
        {
             e.printStackTrace();
        }       
        return "";
    }//end method readFinalQuestionBank

【问题讨论】:

    标签: java arraylist int java.util.scanner


    【解决方案1】:

    int[]integer array 类型。

    intinteger 类型。

    您不能将数组转换为数字。

    【讨论】:

      【解决方案2】:

      您已将变量i 声明为int 数组并使用它来跟踪question[] 的索引。数组中的索引由 0,1,2,3... 表示,它们的类型为常规 int 而不是 int[]。所以你得到了错误int[] cannot be converted to int

      解决方案:

      int[] i = new int[0]; 更改为int i = 0;

      而且您的代码中还有更多问题。您没有增加question[] 的索引值。因此,您总是将结果从 line[] 数组复制到 question[] 的第一个元素中,这使得数组中的所有其他元素都无用。不要使用String array,而是使用StringBuilder 来保存值。

      【讨论】:

        【解决方案3】:

        代码中有多个问题。将 int 声明为整数,初始化 Questions 并且您必须在将 String 分配给 question 之前将其转换为整数。

        int i = 0;
        int [] question = new int [100];
        question[i++] = Integer.parseInt(line[0]);
        

        【讨论】:

          猜你喜欢
          • 2016-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-12
          • 2021-03-08
          • 1970-01-01
          • 1970-01-01
          • 2013-08-21
          相关资源
          最近更新 更多