Reputation: 27
This is some work Which I'd much rather figure out myself although I really cannot seem to sort my code out. On this part of the code I need to provide a menu which the user can select and then will do further function.
Basically all i'm asking is how I go about allowing the user to select an option which will be obtained amongst a Switch statement, although someones got a better idea?
This is my code:
int menuchoice = 1;
String options;
switch (menuchoice)
{
case 1: options = "Transfer";
break;
case 2: options = "Recent transactions";
break;
case 3: options = "Display account details and current balance";
break;
case 4: options = "Quit";
break;
}
System.out.println(options);
I realise that "menuchoice = 1" doesn't allow the user to select the option they want without changing the code?? Which Im finding abit confusing.. how can I go about this?
Upvotes: 0
Views: 3581
Reputation: 209004
You are declaring a new String options
for every case, and the Original hasn't been initialized. System.out.println(options) is using the one in the scope which is the original uninitialized one
String options = "Transfer";
Just use
options = "Transfer";
Change them all
switch (menuchoice)
{
case 1: options = "Transfer";
break;
case 2: options = "Recent transactions";
break;
case 3: options = "Display account details and current balance";
break;
case 4: options = "Quit";
break;
}
Also to get the menu choice from the user, you should use a Scanner
Scanner scanner = new Scanner(System.in); // scans the console.
System.out.println("Enter a menu option: "); // prints to console
int menuOption = scanner.nextInt(); // gets next int from console
Upvotes: 1
Reputation: 1824
You could use a JOptionPane.showInputDialog("your menu here as a String") to allow the user to input (as a String) which option she wants to use, then you can convert the result to int and use the switch to identify the option that was entered.
And yes, you shouldn't create new variables inside the switch, just use the one you created outside it.
Upvotes: 0