Reputation: 11
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;
}
The String Array airlines[] contains 3 letters designating an airline. The random integer airline is used to choose one of those airlines. The random integer number should designate the last 3 characters of an airplanes callsign.
I'm trying to get an output like "BER219", "AAL814" and so on, but upon executing the class, the String callsign is still null :/
Upvotes: 0
Views: 70
Reputation: 1555
Java passes variables by value. If you are testing the value of callsign variable outside this function then it will be null because you have set it to null outside of the assignCallsign method.
To remedy this, you can either:
return the callsign value from the function and set a variable with it.
public String assignCallSign() {
return airlines[airline] + number;
}
String callsign = assignCallSign()
make callsign a member variable of the class, and your code will function as you expect:
private String callsign;
Upvotes: 2
Reputation: 36743
It is difficult to see the issue without seeing the class that is using it.
Speculating this is part of some "Flight" object. This demonstrates the callsign being set and displayed correctly.
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 + "]";
}
}
Output
Flight [callsign=SKW534]
Upvotes: 0