試圖製作一個使用部分填充數組的程序。代碼的開始處理獲取數組大小的用戶輸入,並讓它們輸入要放入數組中的值。然後我希望這些值在輸入時被排序。部分填充數組程序終止運行時間提前
public static void main(String[] args)
{
int userInput;
int[] userArray;
int numElements;
int index;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of values in array (5 to 10): ");
userInput = keyboard.nextInt();
while (userInput < 5 || userInput > 10)
{
System.out.print("Enter number of values in array (5 to 10): ");
userInput = keyboard.nextInt();
}
System.out.println(); //Space, for neatness
userArray = new int[userInput];
for (int item: userArray)
System.out.print(item + " ");
System.out.print("\nEnter an integer value: ");
userInput = keyboard.nextInt();
int numElements = 0;
int index = 0;
if (numElements == userArray.length - 1)
System.out.println("The array is full.");
else
{
while (index < numElements && userArray[index] < userInput)
{
if (userArray[index] != 0) //Shift the array to the right, and add value at the current index as to not overwrite values.
{
for (int i = numElements; i > index; i--)
userArray[i] = userArray[i - 1];
userArray[index] = userInput;
}
userArray[index] = userInput;
index++;
numElements++;
System.out.print("Updated array: ");
for (int item: userArray)
System.out.print(item + " ");
System.out.println("\nEnter an integer value: ");
userInput = keyboard.nextInt();
}
}
}
我的輸出有問題。輸入值後,程序終止。例如(我故意打印空陣列):
Enter number of values in array (5 to 10): 5
0 0 0 0 0
Enter an integer value: 5
對缺少評論感到抱歉。
,請複製粘貼完整代碼。 –