2014-09-19 81 views
-2

我已經實例化一個包含10個字符串的字符串數組。我基本上想讓用戶輸入一個主題名稱,直到完成所有10個字符串,或者如果用戶輸入「q」退出。一旦發生這種情況,應該通過printArray方法打印String數組元素。這是我迄今爲止的內容,但是在「數組元素:」後面的每個值顯示的「空」值總共包含10個字符串。如果我在幾次輸入後輸入「q」,而不是全部輸入十次,則會發生這種情況。我想擺脫「空」值,如果用戶沒有輸入「q」,在第10項之後,它應該顯示10個數組。字符串數組循環打印值null java

{ 
    // Instantiate a String array that can contain 10 items. 
    String[] array = new String[10]; 

    // Read names of subjects into this array 
    // and count how many have been read in. 
    // There may be fewer than 10. 
    Scanner input = new Scanner(System.in); 

    System.out.println("Please enter a subject name or enter q to quit: "); 
    String subject = input.nextLine(); 
    int i=0; 
    while (!"q".equals(subject)) 
    { 
     array[i]=subject; 
     i++; 


     System.out.println("Please enter a subject name or enter q to quit: "); 
     subject = input.nextLine(); 
    } 
    input.close(); 
    System.out.println("The Array Elements:"); 



    // Call printArray to print the names in the array. 
    printArray(array); 
} 


/** 
* Method printArray prints the String values 
* in a partially-filled array, one per line. Only the 
* significant items in the array should be printed. 
*/ 
public static void printArray(String[] args) 
{ 

    for(String val : args) 
     System.out.println(val); 
} 
+0

_but但我相信循環不能正常工作_爲什麼? – 2014-09-19 04:53:23

+1

現在是學習如何使用調試器的好時機:逐步調試代碼,並在繼續時檢查'quit'和'subject'和'input'變量的值。你可能會發現這個問題。 – assylias 2014-09-19 04:54:32

+0

你的while循環甚至沒有開始,因爲你基本上是在說'while'q'不等於'q'' – Krease 2014-09-19 04:54:58

回答

1
String quit = "q"; 
.... 
    while (!"q".equals(quit)) 

你有什麼期望? quit將始終等於「q」,因此從不輸入循環。

您可能需要while (!"q".equals(subject)),因爲subject是您在循環中更改的變量。

+0

adony ma shelom kha? – 2014-09-19 05:12:36

1
String quit = "q"; 

while (!"q".equals(quit)) 

這是一樣的

while(!true) 

所以你永遠不會裏面去while循環

我認爲你必須檢查

while (!subject.equals(quit)) 
0
for(i=0i<10;i++) 
{ 
    System.out.println(array[i]); 
} 

把這個放在你調用函數的地方。 不調用另一種方法來顯示數組。