尝试制作使用部分填充数组的程序。代码的开头处理获取数组大小的用户输入并让它们输入要放入数组中的值。然后我想要在输入值时对值进行排序。
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
很抱歉没有评论。
答案 0 :(得分:1)
你的陈述的这一部分总是错误的!
index < numElements
index和numElements最初都是0。因此,你的while循环只是跳过并完成。
答案 1 :(得分:0)
尝试用此替换代码的最后一部分:
int numElements = 0;
while (numElements < userArray.length ) {
System.out.print("\nEnter an integer value: ");
userInput = keyboard.nextInt();
//insert into the first column
userArray[0] = userInput;
// order the table
for (int i=0 ;i<=(userArray.length-2);i++)
for (int j=(userArray.length-1);i < j;j--)
if (userArray[j] < userArray[j-1])
{
int x=userArray[j-1];
userArray[j-1]=userArray[j];
userArray[j]=x;
}
numElements++;
}
System.out.print("Updated array: ");
for (int item: userArray)
System.out.print(item + " ");
System.out.println("\nEnter an integer value: ");
userInput = keyboard.nextInt();
System.out.println("The array is full.");