variable immediate not have been initialized
Why?
I'm thinking of making five random numbers, but it doesn't work very well.Please let me know.
public class Main
{
static void getrandom5(){
System.out.println("Generating random numbers");
inti;
int nums[] = new int[5];
nums[i]=(int)(Math.random()*(52+1));
for(i=0;i<5;i++){
System.out.println("It is"+nums);
}
}
public static void main (String[]args)
{
getrandom5();
}
}
The variable i
declared, but it did not initialize nums[i]=
and it appears to be an error.
inta;// variable declaration
a = 0; // Initialize variable
intb = 1; // Declare and initialize variables
Note:
Variable light not have been initialized error-Stack Overflow Answer
The reason for the error is that the variable i
has not been initialized and is loaded (which is the same as @cubick's answer).
To make it a little easier to understand, I wrote a comment on what I was doing one line at a time in the program:
// Output string
System.out.println("Generating random numbers");
// Declare variable i (not initialized at this time).In other words, the value of the variable is not determined.)
inti;
// Declare variable nums and initialize with newly reserved array of length 5
int nums[] = new int[5];
// The i-th element of array nums is substituted with a random number (where the value of variable i is not determined, but is reading, causing an error).
nums[i]=(int)(Math.random()*(52+1));
// Loop while increasing i by 1 from 0 to 5
for(i=0;i<5;i++){
// Output a string (although it doesn't say what number of elements of array nums you care about here, so it will behave differently than expected.
System.out.println("It is"+nums);
}
Perhaps what you wanted to do was to increase the variable i
in order while substituting all random numbers in the array nums
.If so, write as follows:
// Loop while declaring variable i and increasing i by 1 from 0 to 5
for(inti=0;i<5;i++){
// Replace random number with i-th element of array nums
nums[i] = (Write the code to generate random numbers here)
}
© 2024 OneMinuteCode. All rights reserved.