Ivana
Ivana

Reputation: 11

Loop to find max value

Hi I'm having a problem to write a loop which finds the largest value.

A list of integers and an integer variable are declared like this: List list; int max; 

Assuming that some values (including negatives!) have been added to the list. i need to find the largest value in list and stores it in max.

//  start of test code

import java.util.*;

public class ListTest

{

private List<Integer> list;

private int max;
public void findMaxInListTest()
        {

list = new ArrayList<Integer>(); // could be a Linked list

list.add(0);
list.add(-99);

list.add(99);
list.add(1320);

list.add(470000);

list.add(12);
list.add(-5000);
list.add(300);
/*#     max = starting value

iterate through list to set max = max value in list

in this case 470000
    */

}

}

I tried using this loop but then encounter an error:

int max = list[0];
  for(int i=470000;i < list.length;i++){
    if(list[i] > max){
      max = list[i];
    }
  }
return max;

do you know which kind of loop that appropriate for this? Thanks

Upvotes: 1

Views: 8921

Answers (5)

moeTi
moeTi

Reputation: 3904

No loop required, use max method from java.utils.Collections (Documentation)

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<Integer>();
        list.add(0);
        list.add(-99);
        list.add(99);
        list.add(1320);
        list.add(470000);
        list.add(12);
        list.add(-5000);
        list.add(300);

        System.out.println(Collections.max(list));
    }
}

Upvotes: 1

Brad Johnson
Brad Johnson

Reputation: 121

for(int i=470000;i < list.length;i++){ 

should be

for(int i=0;i < list.length;i++){ 

Upvotes: 1

Eder
Eder

Reputation: 1884

import java.util.Collections;

Collections.sort(list);
System.out.println(list.get(list.size() - 1));

Upvotes: 2

Dariusz Jędrzejczyk
Dariusz Jędrzejczyk

Reputation: 911

for(int i=470000;i < list.length;i++){

i is the index. put i=0. getting list element for index 470000 throws the exception.

also, list[i] doesn't work in java. use list.get(i). also, list.length doesn't work on lists. use list.size().

You're misinterpreting java List - it's not an array.

Upvotes: 2

Adam Dymitruk
Adam Dymitruk

Reputation: 129526

You need to iterate over the list. Start with i=0 - not 47000.

Hope this helps.

Upvotes: 3

Related Questions