Search code examples
javaarraysstringint

cannot convert int to string array


Hi the problem in the code is at the end finalResult[index]= mark; code, mark gives error. It says cannot convert int to string. How can i fix it ?

    System.out.println("Please choose a criteria (2-7) ?");
    topic = in.nextInt();
    System.out.println("Please enter a mark :");
    int mark = in.nextInt();
    final int size = cols.length;
    String[] finalResult = new String[size];
    int index = 0;

    while(index<finalResult.length ) {
        if (index==topic) {
          finalResult[index]= mark;
        } else {
        finalResult[index]=cols[index];
        }
        index++; 

    }
    }

Solution

  • The problem is here:

    finalResult[index] = mark;
    

    You can't put int number to String array:

    Error:
    incompatible types: int cannot be converted to java.lang.String

    You need to convert number to String before adding to the array.

    You have to change as follows:

    finalResult[index] = String.valueOf(mark);
    

    or

    finalResult[index] = mark + "";