如何声明一个数组列表?

huangapple 未分类评论44阅读模式
英文:

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&lt;Integer&gt; 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 &lt; maxRange.size(); i++) 
  {
      int elementValue = maxRange.get(i);
      if(max &lt; elementValue)
      {
          max = elementValue;
      }
      if (elementValue &lt; min)
      {
          min = elementValue;
      }
  }
  return (max -min) + 1;
}
public class Scratchpad
{
   public static void main(String[] args)
   {
       List &lt;Integer&gt; maxRange = new ArrayList &lt;&gt;();
       
       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>



huangapple
  • 本文由 发表于 2020年5月2日 13:50:28
  • 转载请务必保留本文链接:https://java.coder-hub.com/61555070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定