这是我的类中的练习。我通过了,但我收到了上次打印的空值。你能帮我举几个例子吗?我想理解代码,而不是让它工作;(
谢谢!
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String[] namesWomen = new String[5];
String[] namesMen = new String[5];
String[] names = new String[5];
Scanner reading = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.println("Enter the name: ");
names[i] = reading.nextLine();
System.out.println("Thank you!");
}
for(int i=0; i<5;i++) {
var name = names[i];
if (name.charAt(name.length() - 1) == 'a') {
System.out.println("woman");
namesWomen[namesWomen.length- 1] = name;
} else {
System.out.println("men");
namesMen[namesMen.length- 1] = name;
}
}
System.out.println(Arrays.toString(namesMen));
System.out.println(Arrays.toString(namesWomen));
}
}
当您像对namesWomen
和namesMen
那样实例化一个新数组时,它的所有元素都初始化为null
。在您的代码中,似乎只有一个地方可以更改namesWomen
:中的值
namesWomen[namesWomen.length- 1] = name;
在namesMen
:中更改值的一个地方
namesMen[namesMen.length- 1] = name;
这两次,您都只更改列表中的最后一个元素,因此所有其他元素在整个程序中都保持为null
。