2017-01-15 33 views
-2

試圖製作一個使用部分填充數組的程序。代碼的開始處理獲取數組大小的用戶輸入,並讓它們輸入要放入數組中的值。然後我希望這些值在輸入時被排序。部分填充數組程序終止運行時間提前

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

您聲明的這一部分始終是FALSE!

index < numElements 

index和numElements最初都是0。因此,你的while循環只是跳過並完成。

+0

謝謝你是真的,任何想法如何我可以通過一個while循環移動數組呢?我正在嘗試爲元素找到下一個位置。這是下一個元素大於我想添加的元素的位置。 – grant2088

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.");