Joseph Kraemer
Joseph Kraemer

Reputation: 111

Incompatible type error int[] to int

I am getting an error, incompatible types: int[] cannot be converted to int. Can someone explain why this is happening and what I need to do to fix it? Thanks for the help. Here is my code:

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

Upvotes: 0

Views: 12095

Answers (3)

Prudhvi
Prudhvi

Reputation: 2353

You have declared variable i as an int array and using it to track index of question[]. Indices in arrays are represented by 0,1,2,3... which are of type regular int and not int[]. So you're getting the error int[] cannot be converted to int

Solution:

Change int[] i = new int[0]; to int i = 0;

And also you have more problems in your code. You're not incrementing index value of question[]. So you're always copying the result from line[] array into 1st element of question[] which makes all the other elements in your array useless. Instead of using String array, use StringBuilder to save the value.

Upvotes: 1

Sunil Rajashekar
Sunil Rajashekar

Reputation: 350

You have multiple problems in the code. declare int as integer, initialise Questions and You have to convert String to integer before assigning it to question.

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

Upvotes: 0

DDPWNAGE
DDPWNAGE

Reputation: 1443

int[] is an integer array type.

int is an integer type.

You can't convert an array to a number.

Upvotes: 1

Related Questions