我无法从数组输出中删除空值

时间:2017-06-21 14:20:53

标签: java arrays string java.util.scanner

我希望下面的程序获取用户输入,将其存储在数组中,然后在用户键入stop时重复它。

然而,它将剩下的值打印为100 null,这是我需要删除的内容。我尝试了一些不同的方法,但它不适合我。

这基本上是我到目前为止所得到的(在Stack的其他问题的帮助下):

public static void main(String[] args) {

    String[] teams = new String[100];
    String str = null;
    Scanner sc = new Scanner(System.in);
    int count = -1;
    String[] refinedArray = new String[teams.length];

    for (int i = 0; i < 100; i++) {       
       str= sc.nextLine();


       for(String s : teams) {
           if(s != null) { // Skips over null values. Add "|| "".equals(s)" if you want to exclude empty strings
               refinedArray[++count] = s; // Increments count and sets a value in the refined array
           }
       }

       if(str.equals("stop")) {
          Arrays.stream(teams).forEach(System.out::println);
       }

       teams[i] = str;
    }
}

2 个答案:

答案 0 :(得分:1)

具有固定大小的数组,如果使用任何类的数组,则对于未赋值的值的索引,您将具有空值。

如果您想要一个只使用了值的数组,您可以定义一个变量来存储数组实际使用的大小。
并使用它来创建一个具有实际大小的新数组。

否则你可以使用原始数组,但只在循环String[] teams时迭代到数组的实际大小。

String[] teams = new String[100];
int actualSize = 0;
...
for (int i = 0; i < 100; i++) {       
   ...

   teams[i] = str;
   actualSize++;
   ...
}
   ...
String[] actualTeams = new String[actualSize];
System.arraycopy(array, 0, actualTeams, 0, actualSize);

更好的方法当然是使用自动调整其大小的结构,例如ArrayList

答案 1 :(得分:1)

您只需要告诉您的流要包含哪些元素。您可以更改构建流的行:

   if(str.equals("stop")) {
      //stream is called with a beginning and an end indexes.
      Arrays.stream(teams, 0, i).forEach(System.out::println);
   }