0

In Java, I made an int array, and I want to add several of those values together to get another value in that same array, but I'm (understandably) getting an error message that says "variable might not have been initialized." Here is the code:

public static void random(){
    Random rand = new Random();
    int[] colours = {rand.nextInt(20)+1,rand.nextInt(20)+1,(100-(colours[0]+colours[1]))};

What I want to have happen, here, is for the first element of "rand.nextInt(20)+1" (let's call it "value A") to be added to (what we'll call) value B to get value C (the "100-colours[0]+colours[1]"). I want (100-A+B)=C for my third value. Is there any way I can do this while keeping value C in the array? I'm going to be putting these values through a for loop, and I want each value to correspond with the number of loops (basically, I want one value put out with each loop; loop 1 outputs A, loop 2 outputs B, loop 3 outputs C).

1
  • Calling array when array is not finished initialising is getting you error. And then use shmosel’s method to put value at next position. Commented Dec 27, 2017 at 7:30

1 Answer 1

3

Just default the last element to 0 (or any other value) and then update it in the next line:

Random rand = new Random();
int[] colours = {rand.nextInt(20)+1, rand.nextInt(20)+1, 0};
colours[2] = 100-(colours[0]+colours[1]);
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Solved my problem :] Thank you!! Good method, wicked simple; should've thought of it, but I'm just getting back into Java after a several month hiatus. I appreciate the help.

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.