我已經實例化一個包含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);
}
_but但我相信循環不能正常工作_爲什麼? – 2014-09-19 04:53:23
現在是學習如何使用調試器的好時機:逐步調試代碼,並在繼續時檢查'quit'和'subject'和'input'變量的值。你可能會發現這個問題。 – assylias 2014-09-19 04:54:32
你的while循環甚至沒有開始,因爲你基本上是在說'while'q'不等於'q'' – Krease 2014-09-19 04:54:58