2017-06-21 27 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); 
    }