我希望以下程序能够接受用户输入,将其存储在阵列中,然后在用户键入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;
}
}
也许你可以团队转换到一个列表,然后截断它像它说的https://stackoverflow.com/questions/1279476/truncate-a-list-to -a给定数量的元素 – ZeldaZach
@ZeldaZach在这种情况下不需要截断List。它将只包含添加的元素。 –