字符串数组循环打印值null java

时间:2014-09-19 04:52:27

标签: java arrays eclipse loops sentinel

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

3 个答案:

答案 0 :(得分:1)

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

你期待什么? quit将始终等于" q",因此永远不会输入循环。

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

答案 1 :(得分:1)

 String quit = "q";

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

这与

相同
 while(!true)

所以你永远不会进入while循环

我认为你必须检查

 while (!subject.equals(quit))

答案 2 :(得分:0)

for(i=0i<10;i++)
{
    System.out.println(array[i]);
}

把它放在你调用函数的地方。 不要调用另一种方法来显示数组。

相关问题