0
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 :/

4
  • 4
    Define executing the class. Commented Mar 10, 2015 at 15:33
  • I probably meant running, the german word translates into executing though :') [As in assignCallsign();] Commented Mar 10, 2015 at 15:38
  • 2
    Define running the class. Commented Mar 10, 2015 at 15:39
  • It isn't possible to tell what the problem is without a runnable example. Commented Mar 10, 2015 at 15:53

2 Answers 2

2

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;
    
Sign up to request clarification or add additional context in comments.

1 Comment

just to state the obvious: your second code sniplet returns a String and is therefore not public VOID assignCallSign()
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.