【问题标题】:Why isn't my array saving the results?为什么我的数组没有保存结果?
【发布时间】:2017-02-14 04:06:30
【问题描述】:

我的代码有一个构造函数,它将位置和整数输入到用户希望的选定位置,最多包括 20 个可能的条目。

然后它从我的构造函数中将结果作为数组返回......唯一的问题是它没有保存结果。

我希望它将数组结果保存为用户的输入,并要求用户提供另一个输入,直到所有插槽都被填满,但每次输入时它都应该显示到目前为止的数组。

        Scanner input = new Scanner(System.in);
        int[] arraySize = new int[20];
        while (arraySize.length <= 20){
          System.out.println("Enter the position");
          int arrayPosition = input.nextInt();
          System.out.println("Enter the integer to be inserted here");
          int positionInteger = input.nextInt();
          int[] arrayThatIsntSavingAnything = Insert(arraySize, arrayPosition, positionInteger);
        }       
          System.out.println(java.util.Arrays.toString(arrayThatIsntSavingAnything));
        }

【问题讨论】:

  • 在我看来,您的代码甚至无法编译,因为 arrayThatIsntSavingAnything 是在 while 循环中定义的,并且无法在其外部访问。

标签: java arrays loops insert save


【解决方案1】:

您的arraySize 的长度始终为 20,无论其中填写了什么。因此,它永远不会进入while 循环。您可以启动另一个计数器来跟踪执行的输入数量。另外请注意,您正在检查&lt;=,这可能导致ArrayIndexOutOfBoundsException,因为arraySize[20] 不存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 2013-03-07
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多