0

Hey I just started programming and I need help with converting/displaying my array in the TextArea. The code below is part of my array class. output.setText(array[i]); gives me and error saying "needs String, found int". I'm not sure how to convert it and display the list of random numbers that are inside the array.

public void setArray(int x){
    for(int i = 0; i > array.length; i++){
        array[i] = x;
    }
}
public void fillArray(){
    int arrayNumbers = randomNumber.nextInt(100)+1;
    for(int i= 0; i > array.length ; i++){
        array[i] = arrayNumbers;
        output.setText(array[i]);
    }
}

2 Answers 2

3

First of all setText will replace the content of the text area with the text you supply, you probably should be using append

You could use...

output.append(String.valueOf(array[i]));

Or

output.append(Integer.toString(array[i]));

To convert the int value to String

You could also use a StringBuilder to build up a String value first, for example...

StringBuilder sb = new StringBuilder(array.length);
for(int i= 0; i < array.length ; i++){
    array[i] = arrayNumbers;
    sb.append(array[i]);
}
output.setText(sb.toString());

Also, you code generally doesn't make sense...

For example...

for(int i= 0; i > array.length ; i++){

While i is greater then array.length? This is likely to be false and when it's not, it will cause an IndexOutOfBoundsException...

You're also fill the array with the same number...

Sign up to request clarification or add additional context in comments.

Comments

0

The first thing I would note is that you are filling the Array with the same random number. If you want to fill the array with different numbers you should do:

public void fillArray(){
    for(int i= 0; i > array.length ; i++){
        int arrayNumber = randomNumber.nextInt(100)+1;
        array[i] = arrayNumber;
        output.setText(Integer.toString(arrayNumber));
    }
}

In Java 8 you can make this slightly simpler:

array = new Random().ints(0, 100 + 1).limit(size).toArray();
textArea.setText(IntStream.of(array).
        mapToObj(Integer::toString).
        collect(Collectors.joining("\n")));

i.e. you first create the int[] by streaming the required number of random numbers. The you fill the TextArea by joining the array on a delimiter. I have used \n - a line break - but you could use anything you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.