简体   繁体   中英

Could someone please explain why I can't get the selection variable back from the method showMenu

   int selection = 0;
    showMenu(selection);

   

    


 }
public static int showMenu(int selection) {



    Scanner key = new Scanner(System.in);
    System.out.println("METER CONVERSION\n1) Convert to Kilometers\n2) Convert to Inches\n3) Convert to Feet\n4) Quit the Program");
    System.out.println("Please make a selection: ");
    selection = key.nextInt();
    return selection;

}

I need to know how I can get the value from showMenu back to the variable selection.

The updated value of selection is returned by the showMenu() function. Also, keep in mind that the selection variable in the function's parameter, and the variable with the same name defined before the function is invoked are two different variables.

If you want to use the updated value of selection , you have to do something like this:

int selection = 0;
selection = showMenu(selection);

Or equivalent code:

int selection = showMenu(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM