2017-06-21 28 views
0

我希望以下程序能够接受用户输入,将其存储在阵列中,然后在用户键入stop时将其重复回去。我无法从阵列输出中删除空值

然而,它打印出其余的值为100作为null,这是我需要删除。我尝试了几种不同的方法,但它不适合我。

这基本上就是我(从堆栈中的其他问题有帮助)这么远:

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; 
    } 
} 
+0

也许你可以团队转换到一个列表,然后截断它像它说的https://stackoverflow.com/questions/1279476/truncate-a-list-to -a给定数量的元素 – ZeldaZach

+0

@ZeldaZach在这种情况下不需要截断List。它将只包含添加的元素。 –

回答

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

你只需要告诉你的流什么元素包括。您可以更改行构建流:

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