java - 使用Java循环向ArrayList添加值超出范围时 try catch

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

我想将所有值作为 0.0 添加到大小设置为 MAX=5 的 ArrayList 中。我正在使用 for 循环来添加值。当列表超过最大大小时,我想捕获越界异常。一条消息将输出列表大小应为 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在 for 循环之外,因为 i 的范围位于for内循环。

第二:

作者:ArrayList<Double> myList = new ArrayList<Double>(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 的使用这里不需要。仅针对您的问题而显示。

关于java - 使用Java循环向ArrayList添加值超出范围时 try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47525925/

相关文章:

java - 如何使用 Eclipse 在 Java 中生成 Web 服务客户端

java - hibernate/JPA : only one entry can have specific field value

Java 8 - 三重嵌套 for 循环

java - 使用 for 循环创建多个数组

bash - 用于不包括某些 IP 的 IP 范围的循环

sql-server - 从一个表中选择一个逗号分隔值,并使用 SQL Server 中的函数在另一个表中的 where 条件中使用它

Java StringTemplate 使用外部目录中的文件

java - 如何在 Android 应用程序中设置计时器并为其执行操作

php - JOINS 与 while 语句

c++ - 输入结束后退出 while 循环