我希望以下程序接受用户输入,将其存储在数组中,然后在用户键入 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;
}
}
最佳答案
数组具有固定大小,如果您使用任何类的数组,则未赋值的值的索引将为空值。
如果您想要一个仅包含已使用值的数组,您可以定义一个变量来存储数组实际使用的大小。
并用它创建一个具有实际大小的新数组。
否则,您可以使用原始数组,但在 String[] groups
上循环时仅迭代直到数组的实际大小。
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
。
关于java - 我无法从数组输出中删除空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44678775/