迭代数组时,在C#中索引超出范围异常(Index out of Range exception in C# when iterating through an array)
我有这个代码我用来创建一个程序,它取一个范围并输出到控制台的素数。 我有一个问题,我正在尝试迭代我构建的数组,因此循环应该只使用我的方法的返回值向控制台写入素数值。 我遇到的问题是我将第二个条件设置为
numArray.Length
但它似乎给了我Index out of Range Exception
的Index out of Range Exception
。 我只是希望循环迭代numArray
所有值,并在完成后确定最后一个值是否为素数时停止。public struct Prime { public int x; // constructor for Prime public Prime(int x1) { x = x1; } public int IsPrime(int number) { int i; for (i = 2; i * i <= number; i++) { if (number % i == 0) return 0; } return 1; } } class Program { static void Main(string[] args) { Console.WriteLine("Enter an Integer"); int num1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter a Second Integer of Greater Value"); // int num2 = 0; int num2 = Convert.ToInt32(Console.ReadLine()); /* if (num2temp > num1) { num2temp = num2; } else { Console.WriteLine("You Did Not Enter An Integer Greater Than the First Integer, Please Enter Your Integers Again."); Environment.Exit(0); } */ int index = 1; int[] numArray = new int[num2]; for (int i = num1; i <= num2; i++) { numArray[index] = i; Console.WriteLine(" index: {0} assignment: {1}", index, i); index++; Console.WriteLine("index: {0}",index); } Console.WriteLine("value: {0}", numArray[40]); /* Prime myprime = new Prime(); if (myprime.IsPrime(numArray[12]) == 1) { Console.WriteLine("true"); } else { Console.WriteLine("False"); } */ Prime myprime = new Prime(); int value = 0; for (int y = 1; y <= num2; y++) { if (myprime.IsPrime(numArray[y]) == 1) { value = numArray[y]; Console.Write("{0} \t", value); } }
I have this code I'm using to create a program that takes a a range and outputs to the Console the prime numbers. I have one problem, I'm trying to iterate through the array I built so the loop should only write to the console the values that are prime using my method's return value. The problem I'm having is that I have the second condition set to
numArray.Length
but it seems to give me theIndex out of Range Exception
. I just want the loop to iterate through all values in thenumArray
and stop when it's done figuring out whether the last value is prime or not.public struct Prime { public int x; // constructor for Prime public Prime(int x1) { x = x1; } public int IsPrime(int number) { int i; for (i = 2; i * i <= number; i++) { if (number % i == 0) return 0; } return 1; } } class Program { static void Main(string[] args) { Console.WriteLine("Enter an Integer"); int num1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter a Second Integer of Greater Value"); // int num2 = 0; int num2 = Convert.ToInt32(Console.ReadLine()); /* if (num2temp > num1) { num2temp = num2; } else { Console.WriteLine("You Did Not Enter An Integer Greater Than the First Integer, Please Enter Your Integers Again."); Environment.Exit(0); } */ int index = 1; int[] numArray = new int[num2]; for (int i = num1; i <= num2; i++) { numArray[index] = i; Console.WriteLine(" index: {0} assignment: {1}", index, i); index++; Console.WriteLine("index: {0}",index); } Console.WriteLine("value: {0}", numArray[40]); /* Prime myprime = new Prime(); if (myprime.IsPrime(numArray[12]) == 1) { Console.WriteLine("true"); } else { Console.WriteLine("False"); } */ Prime myprime = new Prime(); int value = 0; for (int y = 1; y <= num2; y++) { if (myprime.IsPrime(numArray[y]) == 1) { value = numArray[y]; Console.Write("{0} \t", value); } }
原文:https://stackoverflow.com/questions/17017830
最满意答案
Pareto_set_List.get(Optimization_Problem.General_Calculation.Get_Another_Solution).add(EncodingUtils.getInt(solution.getVariable(j)));
在此之前,您似乎没有向
Pareto_set_List
添加任何ArrayList
实例,因此ArrayList为空。 当您尝试检索位于Optimization_Problem.General_Calculation.Get_Another_Solution
(看起来为0)的元素时,将引发异常。你可以做的是将一个
ArrayList
添加到Pareto_set_List
,如下所示:Pareto_set_List.add(new ArrayList<Integer>());
Pareto_set_List.get(Optimization_Problem.General_Calculation.Get_Another_Solution).add(EncodingUtils.getInt(solution.getVariable(j)));
Before this point, you don't seem to add any
ArrayList
instances toPareto_set_List
, so the ArrayList is empty. When you try to retrieve the element located atOptimization_Problem.General_Calculation.Get_Another_Solution
(which seems to be 0), the exception is thrown.What you could do is add an
ArrayList
toPareto_set_List
as follows:Pareto_set_List.add(new ArrayList<Integer>());
You can find helpful information here and several links here.
相关问答
更多-
每次用户选择另一个月(难以阅读且容易出错)时,不要进行复杂的计算,而是更好地初始化一些涵盖所有情况的静态模型。 然后,StateChaged处理程序只需选择正确的模型。 以下示例基于新的花式java 8 datetime API: private static String[] initDays( int number ) { String[] result = new String[ number]; for ( int i = 0; i < result.length; i++ ) ...
-
迭代列表中的列表: List
- > dList = new ArrayList<>();
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("A", "B", "C"));
dList.add(Arrays.asList("A", "B", "C"));
for (List
list : dList) { if (list.contains(" ... -
ArrayList不是多线程安全的。 如果在大约另一个线程访问时被一个线程修改,则在运行测试时index >= size可能为true,但在构建消息时为false。 ArrayList is not multithread safe. If it were being modified by one thread at about the time of an access by another thread, index >= size could have been true when the test ...
-
你想要做的是首先在a中添加一些内容因为你总是在外部列表上读取i值,所以我们在外部循环上添加一个新的数组列表。 import java.util.ArrayList; public class abc { public static void main(String[] args) { ArrayList
> a = new ArrayList >(); for(int i=0;i<10; ... -
绘制List的假设图片可能会有所帮助。 这是一个可能的外部列表,其内容如下: 0: [] 1: [a, b, c] 2: [d, e] 3: [] 等等 因此,它与2D阵列不同,因为没有统一的列大小。 所以你可以看到,索引0的外部列表是空的,索引1,有一个包含3个项目的列表,等等。 鉴于此,要迭代List
- > ,您还必须每次都检查内部列表的大小: for (int x = 0; x < list.size(); x++) {
for (int y = 0; y < list ...
-
Pareto_set_List.get(Optimization_Problem.General_Calculation.Get_Another_Solution).add(EncodingUtils.getInt(solution.getVariable(j))); 在此之前,您似乎没有向Pareto_set_List添加任何ArrayList实例,因此ArrayList为空。 当您尝试检索位于Optimization_Problem.General_Calculation.Get_Another_So ...
-
Java ArrayList避免IndexOutOfBoundsException(Java ArrayList avoiding IndexOutOfBoundsException)[2022-11-19]
只需使用列表的大小(不是数组): if (x.size() <= index || x.get(index) == null) { ... } 或者,如果你想检测一个非空值的有效索引,你可以使用: if (index < x.size() && x.get(index) != null) { ... } 在这两种情况下,如果表达式的第一部分检测到索引对列表无效,则不会进行get调用。 请注意,“没有元素6”(因为列表中没有7个元素)和“存在元素6但它的值为空”之间存在逻辑上的区别 - 在 ... -
问题 首先,这里的ec是ArrayList
,这意味着ec.get(i)应该返回Double[]而不是ArrayList 。 其次, double和Double是完全不同的类型。 您不能简单地在代码上使用row.toArray(new double[row.size()]) 。 解决方案 1。 如果你想要一个真正的Doubles 2D ArrayList ,那么ec的类型应该是ArrayList > 。 但是因为我们不能使用toArray ... -
ArrayList While Loop给出IndexOutOfBoundsException(ArrayList While Loop Gives IndexOutOfBoundsException)[2023-04-17]
以下两行将始终抛出IndexOutOfBoundsException - 只要您的数组大小为奇数,就会发生这种情况: int n = tournamentArrayList.size(); //... winners.add(tournamentArrayList.get(n)); 由于列表索引从0开始,因此列表中的最后一个元素是索引size() - 1 。 The following two lines will always throw an IndexOutOfBoundsException - w ... -
折叠2D ArrayList(Collapse 2D ArrayList)[2021-07-22]
没有Java 8,您必须使用循环。 使用addAll(..)确实摆脱了其中一个。 public ArrayListgetList(){ ArrayList result = new ArrayList (); for(ArrayList i : list_){ result.addAll(i); } return result; } 此外,诸如ArrayList之类的泛型类型必须是对象 ...