当我尝试打印一些Java代码时,它返回null。我知道我的代码中缺少一些东西,但我不确定是什么。请注意,我对Java相对较新。我几乎肯定它是addGuest方法中的东西。
import java.util.Scanner;
public class PartyParticipants {
int sizeOfList = 3;
static String[] guestList;
String hostName;
String addGuest;
static int Guest;
Scanner stdIn = new Scanner(System.in);
public PartyParticipants(int size, String host) {
sizeOfList = size;
hostName = host;
}
public static void main(String[] args)
{
PartyParticipants party = new PartyParticipants(3, "David Beckham");
party.addGuest("Roberto Baggio");
party.addGuest("Zinedine Zidane");
party.addGuest("Roberto Baggio");
party.addGuest("Johan Cruyff");
party.addGuest("Diego Maradona");
party.printParty();
}
private void addGuest(String string) {
for (int i=0; i<sizeOfList; i++)
{
Guest++;
}
if (sizeOfList > 3)
{
System.out.println(Guest + " cannot come to the party. The guest list is full.");
}
}
public void printParty()
{
{
System.out.println("Guest list for " + hostName + "'s party:");
System.out.println(guestList);
}
}
}
答案 0 :(得分:1)
您好,您需要初始化您的阵列.. 喜欢做这里的事情
static String[] guestList = new String[sizeOfList ];
static int Guest = 0;
并更改addGuest方法
private void addGuest(String string)
{
if (Guest <= 3)
{
System.out.println(Guest + " cannot come to the party. The guest list is full.");
}
else
{
guestList[Guest]=string;
Guest++;
}
}
printParty方法的一个小改动..
public void printParty()
{
System.out.println("Guest list for " + hostName + "'s party:");
for(int i=0;i<guestList.length;i++)
System.out.println(guestList[i]);
}
阅读更多关于java ..
的信息