【问题标题】:I cannot remove null values from array output我无法从数组输出中删除空值
【发布时间】:2017-06-21 14:20:53
【问题描述】:

我希望以下程序接受用户输入,将其存储在数组中,然后在用户键入 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;
    }
}

【问题讨论】:

  • 也许您可以将团队转换为列表,然后像 stackoverflow.com/questions/1279476/… 中所说的那样截断它
  • @ZeldaZach 在这种情况下不需要截断List。它将仅包含已添加的元素。

标签: java arrays string java.util.scanner


【解决方案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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      相关资源
      最近更新 更多