【问题标题】:try-catch when adding value to ArrayList is out of bound using loop Java使用循环Java向ArrayList添加值时的try-catch超出范围
【发布时间】:2018-05-11 13:50:25
【问题描述】:

我想将所有值作为 0.0 添加到大小设置为 MAX=5 的 ArrayList 中。我正在使用 for 循环来添加值。当列表超过 MAX 大小时,我想捕获一个越界异常。一条消息将输出列表大小应为 5 的原因。然后它将打印出列表值,即 5“0.0”。 我会通过将 MAX 值更改为 8 来测试它:

try {   
for (int i=0; i<8; i++) 
myList.add(0.0);

我尝试将 try{} 放在循环中,并将 add() 放在 while 循环之后。输出要么没有捕捉到异常,要么不返回任何东西。我在下面的代码不返回任何内容。 我一定是问错了问题,因为我似乎找不到答案。或者我的逻辑完全错误......我会很感激任何指导!

//This code doesn't return anything
import java.util.ArrayList; 
public class Values {
private static final int MAX = 5;
private ArrayList<Double> myList = new ArrayList<Double>(MAX); 

public Values()  {

try {   
for (int i=0; i< MAX; i++) {
    myList.add(0.0);
while ( i <0 || i > MAX) {}}    
}
catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
System.out.println("ArrayList size allowed at" + MAX);}

for (Double myList: myList) 
System.out.println(myList);
}

【问题讨论】:

  • i 无法解析为变量,这意味着您从未声明过 i
  • 在你的 for 循环后面添加一些花括号。否则它在下一行的唯一“活动”。一旦你将 while 循环括在花括号内,你的错误就消失了
  • 尽管您使用MAX 长度声明了您的列表,并且如果您要添加更多,它会在内部默默地增加它的长度并相应地进行调整。最好的办法是检查 MAX 并抛出你自己的异常或任何现有的异常。
  • for 循环在 'mylist.add(0.0);' 行之后完成。所以变量'i'在'while'循环中是未知的。尝试正确格式化您的代码,然后您会更容易看到。

标签: java for-loop while-loop try-catch indexoutofboundsexception


【解决方案1】:

第一: 因为i 的范围在for 循环之内,所以您必须在for 循环之外声明i

第二次:

ArrayList&lt;Double&gt; myList = new ArrayList&lt;Double&gt;(MAX); 你没有固定List 的大小。它只是设置它的初始容量。

你需要像下面这样的东西(简而言之):

int MAX = 5;

        ArrayList<Double> myList = new ArrayList<Double>(5);

        try {
            for (int i = 0; i < 8; i++)// to throw IndexOutOfBoundsException
            {
                if(myList.size()>MAX)
                    throw new IndexOutOfBoundsException("My message");
                myList.add(0.0);
            }
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Exception : "+e.getMessage());

        }

注意:这里不需要使用IndexOutOfBoundsException。仅针对您的问题显示。

【讨论】:

  • 感谢您的澄清!我明白我做错了什么。顺便说一句,我将此代码更改为 if(myList.size() >=MAX 并且效果很好!
  • @CocoBeans 乐于助人:)
【解决方案2】:

for 语句中声明的i 变量的作用域仅限于for
因此,您将永远无法在 while 语句中使用它。

一条消息将输出列表大小应为 5 的原因。

IndexOutOfBoundsException 在这里帮不了你,因为它永远不会升起。
您无法访问超出列表范围的索引。
您只在其中添加元素,List.add()ArrayList.add() 并没有在它们的 javadoc 中指定任何异常。

现在,如果您在大小为 4 的列表上执行 list.get(4),则异常将上升为:

E java.util.ArrayList.get(int index)

。 . .

投掷

IndexOutOfBoundsException - 如果索引超出范围(索引 = 大小())

为确保您不超过列表中特定数量的元素,您必须明确检查它。

在您的实际代码中,您可以指定一个入口点以在列表中添加元素并在那里进行检查:

for (int i=0; i< MAX; i++) {
    addInList(0.0));
}

public void addInList(Double value){
  if (doubles.size() > MAX){
    System.out.println(e.getMessage());
    System.out.println("ArrayList size allowed at" + MAX);}

    for (Double myList: myList) 
     System.out.println(myList);
   }
  }
  doubles.add(value);
}

【讨论】:

    【解决方案3】:

    您作为 ArrayList 构造函数参数传递的 MAX 值没有按照您的预期进行。这是一个初始能力。这意味着当您第一次初始化 ArrayList 时,您希望它能够存储至少数量作为构造函数参数传递的值。

    为了实现您的要求,我建议您使用关键字extends Exception 创建您自己的“YourException”(根据您的喜好命名),使其表现得像其他异常一样。然后,在尝试将下一个值添加到 ArrayList 时,如果超出了它的大小,则应该在将每个新值添加到 ArrayList 时进行一些检查。如果它发生了,那么你throw new YourException()

    另一种可能性是 throw new IndexOutOfBoundsException 而不是抛出 YourException,但我认为这不是一个好主意 - 根据 ArrayList 没有边界的事实,这可能有点令人困惑。

    【讨论】:

      猜你喜欢
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多