简体   繁体   English

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

[英]I cannot remove null values from array output

I want the folowing program to take user input, store it in the array then repeat it back when the user types stop . 我希望以下程序接受用户输入,将其存储在数组中,然后在用户键入stop时将其重复。

However it prints out the rest of the values upto 100 as null , this is what I need to remove. 但是,它将剩下的值打印为null最多100个,这就是我需要删除的值。 I've tried a few different methods but it's just not working for me. 我尝试了几种不同的方法,但是对我来说不起作用。

This is basically what I've got so far (with help from other questions on Stack): 基本上这就是我到目前为止(在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;
    }
}

An array as has a fixed size and if you use an array of an any class, you will have null value for indexes of the values not valued. 数组as具有固定的大小,如果使用任何类的数组,则对于未赋值的索引将具有null值。

If you want to have a array with only used values, you could define a variable to store the size really used by array. 如果您希望只有一个使用值的数组,则可以定义一个变量来存储数组实际使用的大小。
And use it to create a new array with the actual size. 并使用它来创建一个具有实际大小的新数组。

Otherwise you could use the original array but iterating only until the actual size of the array when you loop on String[] teams . 否则,您可以使用原始数组,但只能在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);

A better way is of course using a structure that adjusts automatically its size such as an ArrayList . 当然,更好的方法是使用自动调整其大小的结构,例如ArrayList

You just need to tell your stream what elements to include. 您只需要告诉您的流包括哪些元素。 You can change the line constructing the stream: 您可以更改构造流的行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM