Issue
I'm trying to write a util to handle the max/min of the arraylist elements.
In my code, I first set the if conditionyour textif (list.size()!= 0) ;
to ensure that the list has elements:
public static int getMin(ArrayList<Integer> list)
{
int tmp = -1;
if (list.size()!= 0) ;
{
tmp = list.get(0);
for (int i = 0; i < list.size(); i++)
{
if (list.get(i) < tmp)
{
tmp = list.get(i);
}
}
return tmp;
}
}
but the IDE always indicate that the line:tmp = list.get(0);
is causing indexOutofBounds
exception. Why does the if condition I set not working? Maybe it is the static that makes this function not working as I wish. How can I correctly do it?
My whole code is shown below:
package util;
import java.util.ArrayList;
public class ListUtils
{
public static void sort(ArrayList<Integer> list)
{
for (int i = 0; i < list.size() - 1; i++)
{
for (int j = 0; j < list.size() - 1 - i; j++)
{
if (list.get(j) > list.get(j + 1))
{
int tmp = list.get(j);
list.set(j, list.get(j + 1));
list.set(j + 1, tmp);
}
}
}
}
public static int getMax(ArrayList<Integer> list)
{
int tmp = -1;
if (list.size() !=0) ;
{
tmp = list.get(0);
for (int i = 0; i < list.size(); i++)
{
if (list.get(i) > tmp)
{
tmp = list.get(i);
}
}
}
return tmp;
}
public static int getMin(ArrayList<Integer> list)
{
int tmp = -1;
if (list.size()!= 0) ;
{
tmp = list.get(0);
for (int i = 0; i < list.size(); i++)
{
if (list.get(i) < tmp)
{
tmp = list.get(i);
}
}
return tmp;
}
}
//求平均值
public static float getAvg(ArrayList<Integer> list)
{
int sum = -1;
float avg = -1;
if (list.size() != 0) ;
{
for (int i = 0; i < list.size(); i++)
{
sum += list.get(i);
}
avg = (float) sum / list.size();
return avg;
}
}
}
```java
Fix the code to make it robust to handle the 0 element condition.
Solution
You have a ;
after your if statement which ends the block right there and making whats inside the block to always execute
Answered By - Yonatan Nir
Answer Checked By - Timothy Miller (JavaFixing Admin)