首页 \ 问答 \ 迭代数组时,在C#中索引超出范围异常(Index out of Range exception in C# when iterating through an array)

迭代数组时,在C#中索引超出范围异常(Index out of Range exception in C# when iterating through an array)

我有这个代码我用来创建一个程序,它取一个范围并输出到控制台的素数。 我有一个问题,我正在尝试迭代我构建的数组,因此循环应该只使用我的方法的返回值向控制台写入素数值。 我遇到的问题是我将第二个条件设置为numArray.Length但它似乎给了我Index out of Range ExceptionIndex 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 the Index out of Range Exception. I just want the loop to iterate through all values in the numArray 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
更新时间:2023-10-16 20:10

最满意答案

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 to Pareto_set_List, so the ArrayList is empty. When you try to retrieve the element located at Optimization_Problem.General_Calculation.Get_Another_Solution (which seems to be 0), the exception is thrown.

What you could do is add an ArrayList to Pareto_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 ...
  • 只需使用列表的大小(不是数组): 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 ...
  • 以下两行将始终抛出IndexOutOfBoundsException - 只要您的数组大小为奇数,就会发生这种情况: int n = tournamentArrayList.size(); //... winners.add(tournamentArrayList.get(n)); 由于列表索引从0开始,因此列表中的最后一个元素是索引size() - 1 。 The following two lines will always throw an IndexOutOfBoundsException - w ...
  • 没有Java 8,您必须使用循环。 使用addAll(..)确实摆脱了其中一个。 public ArrayList getList(){ ArrayList result = new ArrayList(); for(ArrayList i : list_){ result.addAll(i); } return result; } 此外,诸如ArrayList之类的泛型类型必须是对象 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。