英文:
How to declare an array list?
问题
// 代码部分不要翻译
private int firstElement;
public int maxRange(ArrayList<Integer> arr)
{
if (arr.size() == 0)
{
return 0;
}
if (arr.size() == 1)
{
return 1;
}
int FirstElement = arr.get(0);
int max = firstElement;
int min = firstElement;
for (int i = 0; i < arr.size(); i++)
{
int elementValue = arr.get(i);
if (max < elementValue)
{
max = elementValue;
}
if (elementValue < min)
{
min = elementValue;
}
}
return (max - min);
}
public class Scratchpad
{
public static void main(String[] args)
{
List<Integer> maxRange = new ArrayList<>();
maxRange.add(3);
maxRange.add(11);
maxRange.add(25);
maxRange.add(48);
System.out.println(maxRange);
}
}
英文:
The objective is trying to create a code that gets the difference of the max and min number of the Array List.
As a beginner I am having trouble understanding why I get that maxRange is not declared in my code.
private int firstElement;
public int maxRange(ArrayList<Integer> arr)
{
if (maxRange.size() ==0)
{
return 0;
}
if (maxRange.size()==1)
{
return 1;
}
int FirstElement = maxRange.get(1);
int max = firstElement;
int min = firstElement;
for ( int i =0; i < maxRange.size(); i++)
{
int elementValue = maxRange.get(i);
if(max < elementValue)
{
max = elementValue;
}
if (elementValue < min)
{
min = elementValue;
}
}
return (max -min) + 1;
}
public class Scratchpad
{
public static void main(String[] args)
{
List <Integer> maxRange = new ArrayList <>();
maxRange.add(3);
maxRange.add(11);
maxRange.add(25);
maxRange.add(48);
System.out.println(maxRange);
}
}
</details>
# 答案1
**得分**: 0
如果代码清单都在一个文件中,问题就在于 `firstElement` 和 `maxRange` 被声明在 `Scratchpad` 类的外部。它们应该在类内部。
<details>
<summary>英文:</summary>
If the code listing is all in one file then the problem is that `firstElement` and `maxRange` are declared outside of the `Scratchpad` class. They should be inside it.
</details>
专注分享java语言的经验与见解,让所有开发者获益!
评论