import java.util.Arrays;
public class ArraysLab1
{
static String[] PresidentNames = new String[5];
public static void main(String[] args)
{
//Declare an array of 5 strings
String[] PresidentNames = {"George Bush", "William J. Clinton", "George W. Bush", "Barrack H. Obama", "Donald J. Trump"};
//Print the array values using the printPresidentNames method
ArraysLab1.printPresidentNames();
//Sort the array of names
Arrays.sort(PresidentNames);
//Reprint the array values using the printPresidentNames method
ArraysLab1.printPresidentNames();
}
public static void printPresidentNames()
{
System.out.println(Arrays.toString(PresidentNames));
}
}
尝试使用方法printPresidentNames输出数组PresidentNames的内容,我得到的输出是[null,null,null,null]
答案 0 :(得分:0)
将main()
方法的第一行更改为:
PresidentNames = new String[] {"George Bush", "William J. Clinton", "George W. Bush", "Barrack H. Obama", "Donald J. Trump"};
因为PresidentNames
是类中的一个字段,因此您需要对其进行初始化。在当前代码中,它被定义为main()
方法的局部变量。这是有关班级成员的好explanation。