我已经实例化了一个包含 10 个字符串的字符串数组。我基本上想要求用户输入主题名称,直到所有 10 个字符串都完成,或者用户输入“q”退出。一旦发生这种情况,应通过 printArray 方法打印字符串数组元素。这是我到目前为止所拥有的,但我得到一个“空”值,在“数组元素:”之后为每个值显示一个“空”值,总共构成 10 个字符串。如果我在几个条目而不是全部十个之后输入“q”,就会发生这种情况。我想去掉“null”值,如果用户没有输入“q”,在第 10 个条目之后,它应该显示 10 个数组。
{
// 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);
}