Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda