为什么我的数组不保存结果?

问题描述:

我的代码有一个构造函数,它将位置和整数输入到所选位置,如用户所希望的一样,包括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)); 
     } 
+0

在我看来,你的代码甚至不会编译,因为'arrayThatIsntSavingAnything'是在while循环中定义的,并且不能在其外部访问。 –

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