String callsign;
String airlines[] = {"DLH","BER","TUI","EZY","ACA","AAL","FDX","SKW","ABY","SWR"};
public void assignCallsign()
{
Random r = new Random();
int airline = r.nextInt(10);
int number = r.nextInt(900) + 100;
callsign = airlines[airline] + number;
}
String Array airlines []包含3个指定航空公司的字母。 随机整数航空公司用于选择其中一家航空公司。随机整数应指定飞机呼号的最后3个字符。
我试图得到像" BER219"," AAL814"依此类推,但在执行该类时,String调用符号仍然为null:/
答案 0 :(得分:2)
Java按值传递变量。如果您在此函数之外测试callign变量的值,那么它将为null,因为您已在assignCallsign方法之外将其设置为null。
要解决此问题,您可以:
从函数返回callign值并用它设置变量。
public String assignCallSign() {
return airlines[airline] + number;
}
String callsign = assignCallSign()
使callign成为该类的成员变量,您的代码将按预期运行:
private String callsign;
答案 1 :(得分:0)
如果没有看到正在使用它的类,很难看到问题。
推测这是一些“飞行”对象的一部分。这表明呼号正确设置和显示。
public static void main(String[] args) {
Flight flight = new Flight();
flight.assignCallsign();
System.out.println(flight);
}
private static class Flight {
private static final String AIRLINES[] = { "DLH", "BER", "TUI", "EZY", "ACA", "AAL", "FDX", "SKW", "ABY", "SWR" };
private String callsign;
public void assignCallsign() {
Random r = new Random();
int airline = r.nextInt(10);
int number = r.nextInt(900) + 100;
callsign = AIRLINES[airline] + number;
}
@Override
public String toString() {
return "Flight [callsign=" + callsign + "]";
}
}
输出
Flight [callsign=SKW534]