I need to be able to use one for loop to fill an array and then use the last int given as input as the threshold value. Then I am trying to use another for loop to compare values in the array to the threshold value and if they are less than the value I will put them to output. I have the code nearly completed and while it may be chunky I have it working up until I make the comparison to the array, it is saying my maxValue int is not initialized even though it was assigned a value in the first loop. Please let me know where I am going wrong, I am lost.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] userValues = new int[20]; // List of integers from input
int numVals;
int maxValue;
int i;
// The first input is to set the number of values that will be inputted.
numVals = scnr.nextInt();
// The first for loop that sets the values for the array.
for (i = 0; i < numVals; i++) {
userValues[i] = scnr.nextInt();
}
// The second for loop that sets the max value. Probably a better way to do this.
for (i = numVals - 1; i > numVals - 2; i--) {
maxValue = userValues[i];
}
// This third for loop is where the error is coming from.
for (i = 0; i < numVals; i++) {
if (userValues[i] <= maxValue) {
System.out.print(userValues[i] + ",");
}
}
}
}
This is the error message I am receiving: LabProgram.java:22: error: variable maxValue might not have been initialized if (userValues[i] <= maxValue) {
I found a way to get around my problem, feel like I cheated and that there is probably a better way to make this work so any feedback would be great, but it passed the tests so it works for me.