Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda