Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
is there a way to use a variable in another method without using a parameter?

there is a variable called (limitOfPassengers) in the first method called (addFlight), asking the user to enter a number for the limit then save it in the variable. then i want to use this input in another method called (addPassengerToTheFlight) with an if statement to check if the added passengers doesn't exceed the given limit number.

if i use a parameter in the second method there will be an error on a switch method. What should i do?

The code is too long but here are the codes issue

 switch (choice) {
                case 1: {
                    airway.addFlight();
                    break;
                }
                case 2: {
                    System.out.println("\t\t\t\tPlease Enter Detail of Passenger");
                    airway.addPassengersToFlight();
                    break;

                }
// the first method
public void addFlight()
    {
int limitOfpassengers;
System.out.print("Enter passenger limit:   ");
        limitOfpassengers=ss.nextInt();
}

//the second method

    public void addPassengersToFlight() {
if (flight.getPassengerLimit() <= limitOfpassengers) {
                flight.addPassengers(passengers);
                System.out.println("New Passenger is Added!");
            } else {
                System.out.println("!!!No More Space for Passenger!!!");
            }
}

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Is there a way to use a variable in another method without using a parameter?

Yes. Here is one way:

public class MyClass {

  private int myVar;

  public MyClass() {
    myVar = 0;
  }

  public void incrementMyVar() {
    myVar++;
  }
  
  public int getMyVar() {
    return myVar;
  }
}

The specific issue you have in your provided code is that the scope of limitOfPassengers is limited to the addFlight() method. Search for "java variable scope" for more details.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!