Rei - 1 year ago 89
Java Question

# finding maximum number in ArrayList

this is my practice before my upcoming test, I'm trying to make the user input a number. And all elements in array1 that is below the user's number, will be put in a new ArrayList.
and then I'm trying to print only the highest number in that ArrayList. If the user input is lower than all number in array1, it will return -1.
here is my code, however, when I put 920, it still returns -1, I think there's something wrong with my code to find highest number in ArrayList. Can you guys please tell me what is wrong?

``````static Scanner sc = new Scanner(System.in);
static int[] array1 = {900, 885, 989, 1000, 1500, 1243, 999, 915};

public static int blabla(int[] a, int b) {

Integer d = -1;
ArrayList<Integer> al = new ArrayList<Integer>();

for (int i = 0; i < array1.length; i++) { // this is to find all numbers in array1 that is below user's number, and add it to the ArrayList
if (b > array1[i]) {
} // if
} // for

outerloop: // and this function below is to find maximum number in ArrayList
for (int g = (al.size()-1); g == 0; g--) {
for (int j = 0; j <=(g-1); j++) {
if (al.get(j) > al.get(g)) {
break;
}
else if(j == (g-1)) {
if (al.get(g) > al.get(j)){
d = al.get(g);
break outerloop;
}
}
} //for^2
} // for
return d;
} // priceisright
``````

``````static Scanner sc = new Scanner(System.in);
static int[] array1 = {900, 885, 989, 1000, 1500, 1243, 999, 915};

public static int blabla(int[] a, int b) {

Integer d = -1;
ArrayList<Integer> al = new ArrayList<Integer>();
``````

At this point, a1 is an empty array, so a1.length = 0, this loop never gets executed.

``````    for (int i = 0; i < a1.length; i++) {
// this is to find all numbers in array1 that is below user's number,
// and add it to the ArrayList
if (b > a1[i]) {
} // if
} // for
``````

a1 is still empty there, the second loop won't do anything either.

``````    // and this function below is to find maximum number in ArrayList
outerloop:
for (int g = (al.size()-1); g == 0; g--) {
for (int j = 0; j <=(g-1); j++) {
if (al.get(j) > al.get(g)) {
break;
}
else if(j == (g-1)) {
if (al.get(g) > al.get(j)){
d = al.get(g);
break outerloop;
}
}
} //for^2
} // for
return d;
} // priceisright
``````

``````    // Finds the greater value in values that is below maximum.
// Returns -1 if none is found.
public static int blabla(int[] values, int maximum) {
int best_value = -1;
for (int value : values) {
if (value < maximum && value > best_value) {
best_value = value;
}
}

return best_value;
}
``````

You can replace `int[] values` by `List<Integer> values` if your values are in an ArrayList.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download