1

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

2

5 Answers 5

3

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

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

2
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.

1 Comment

also make max = list.get(0); so you initialize your max, if a number in the list is bigger than the first item,then you replace max with that.
2
import java.util.Collections;

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

Comments

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

should be

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

Comments

1

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));
    }
}

Comments

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.