Using switch statements in a while loop - java

I'm trying to use switch statements in a while loop in Java, but there is something going wrong. Please have a look at a sample code below which explains my problem:
Scanner input=new Scanner(System.in);
int selection = input.nextInt();
while (selection<4)
{ switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
}
If I run this code, the output is as follows:
1
Please enter amount
2000
1. Transfer
2.Check balance
3.Recharge
Please enter amount
2
1. Transfer
2.Check balance
3.Recharge
Please enter amount
When I enter the amount, I would then like to choose another option - and the output should be according to the option chosen (you should probably be knowing what I want this code to do). Could someone please help correct the code?
Thanks

You currently get and set the selection value once and before the while loop, and so there is no way to change this from within the loop. The solution: Get your next selection value from the Scanner object inside of the while loop. To understand this, think the problem out logically and be sure to walk through your code mentally and on paper as the issue is not really a programming issue but rather a basic logic issue.
Regarding:
Could someone please help correct the code?
Please don't ask us to do this and for several reasons.
This is not a homework completion service
You're harming yourself by asking others to change the code for you, as you learn how to code by writing code.
Really this is a basic simple issue that you have the ability to fix on your own. Please give it a try, and only if the attempt doesn't work, then show us your attempt.

You're forgetting to ask for the selection again. It's not going to change once it's been entered.
Scanner input=new Scanner(System.in);
int selection = input.nextInt();
while (selection<4)
{
switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
selection = input.nextInt(); // add this
}
You could even use a do...while loop instead to avoid writing input.nextInt(); twice
Scanner input=new Scanner(System.in);
int selection;
do
{
selection = input.nextInt();
switch(selection){
case 1:
System.out.println("Please enter amount");
double amount=input.nextDouble(); //object of scanner class
break;
case 2:
System.out.println("Enter ID number");
break;
case 3:
System.out.println("Enter amount to be credited");
break;
}
System.out.println("1. Transfer\n2.Check balance\n3.Recharge");
}
while(selection < 4);

Case must be bigger than 4, in your case the cases are less than 4. so you won't quit the loop, basically the break statement breaks the switch and jumps to loop, but than the loop is again less than 4 so it jumps again into the switch and so on. Fix the Sizes of your cases, maybe just make an
(selection != 1 || selection != 2 || selection !=3 || selection !=4)

Related

java currency calculator pausing swtich to give output back to user

first question:
There is a do while loop, within the do section there is a switch. After selection case 1, some calculations are done, two options can result as shown in the If statement. My problem is code runs until the break; then just goes straight back to the menu loop. My question: how do i get the program to print the output for the user, then continue the menu loop?
Second question:
In case 1 there are two resulting options, the first being a failed response. from here, how do i get the program to loop back to the start of case 1 to ask for user input again? Even back to the main menu would be fine.
public static void showMenu() {
System.out.print('\u000c');
System.out.println("1 - Compute Change \n");
System.out.println("2 - Estimate Feast \n");
System.out.println("3 - \n");
System.out.println("4 - \n");
System.out.println("5 - I'm broke, get me out of here\n");
System.out.println("Select Option:\n");
}
public StackPost() {
System.out.println("Welcome to the Bank of Winterfell");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection) {
case 1:
// get input, compute then decision:
if (something<somethingElse) {
// false response -
} else {
// correct response - system prints out some stuff back to user, back to main
// menu loop
}
break;
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
You could print "Press enter to continue" (or whatever you want to give notice of before locking the program), and add a call to Scanner#nextLine() before your break. This will lock the progression 'till user presses enter.
case 2:
// Some code here...
// Done, now show result and tell user to press any key to continue
System.out.println("Some fancy result from case handle code");
System.out.println("Press enter to continue...");
in.nextLine();
break;
You could add a while-loop that won't let the code continue 'till whatever input is expected in the first case is acceptable.
case 1:
System.out.println("Some handle that tells user to input something, and what is acceptable");
String input = null;
while(!(input = in.nextLine()).equals("something")) {
System.out.println("Wrong input, try again...");
}
// Input is acceptable, now do something with it...
System.out.println(input);
System.out.println("Press enter to continue...");
in.nextLine();
break;
Be aware, in your code, you call Scanner#nextInt(), and #nextInt doesn't consume the \n from pressing enter, and will thus be transferred into the switch case's usage of #nextLine(). You could avoid this with selection = Integer.parseInt(in.nextLine()).
You can use achieve it by:
For First question: Using return statement in case of correct response.
For Second question: Using while loop in case 1
After implementaing the proposed solution the StackPost() method will look like following. You can see the complete working code here:
public static void StackPost()
{
System.out.println("Welcome to the Bank of Winterfell");
try(Scanner in = new Scanner(System.in))
{
int selection;
do
{
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
// get input, compute then decision:
while(true)
{
int something = in.nextInt();
int somethingElse = in.nextInt();
if (!(something<somethingElse)) {
// correct response - system prints out some stuff back to user, back to main
System.out.println("Print here the result");
// menu loop
return;
}
// false response - continue for next iteration in while-loop
}
//No need of 'break;' here
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
}
Note: It is best practice to use try-with-resources while handling system resources which implements AutoCloseable interface.

Bad Exception Handling? Program keeps looping?

So I'm currently dealing with this [keep in mind I cut most of the code out cause it's quite long]
int choice = 0;
while (choice != 7){
System.out.println("--- Mathematical Calculator ---");
System.out.println("");
System.out.println("Pick an operation from the list - Use nos. 1 to 7");
System.out.println("1) Multiplication");
System.out.println("2) Division");
System.out.println("3) Addition");
System.out.println("4) Subtraction");
System.out.println("5) Find the area of a regular object");
System.out.println("6) Find the volume of a regular object");
System.out.println("7) Exit Program");
**boolean ok = false;
do {
try{
choice = userInput.nextInt();
ok = true;
} catch (InputMismatchException e){
System.out.println("Invalid input");
}
}
while (ok = false);**
switch (choice) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
System.out.println("Thanks for using my program");
System.out.println("Program terminated");
break;
default: System.out.println("Invalid choice");
}
}
userInput.close();
}
So currently, when I run the program and enter something that is NOT an integer, the program will give the following output:
--- Mathematical Calculator ---
Pick an operation from the list - Use nos. 1 to 7
1) Multiplication
2) Division
3) Addition
4) Subtraction
5) Find the area of a regular object
6) Find the volume of a regular object
7) Exit Program
Invalid input
Invalid choice
Over
And over
And over
I know I've probably done something wrong with the exception handling (program works fine with valid input), but I really don't know how I can fix it.
Help?
You need to catch the \n\r with an userInput.nextLine() in your exception and it stops printing for ever like this
catch (InputMismatchException e){
System.out.println("Invalid input");
userInput.nextLine();
}
while (ok = false); should be while (ok == false);, or while (!ok);.
ok = false is an assignment.
Also, I guess you have intentionally left the cases empty, but even so, make sure that you put a break; on each of them, otherwise the option 7 will always be executed.
EDIT: for the infinite loop, you should also do what Kevin Esche suggests in his answer (+1).

Java: Switch statement not calling methods properly

I am having trouble getting my menu below to run from my driver. The program will execute, however it will not display my menu until I enter a number. After that it will display properly, and it reads selection properly, but will not call the methods I have listed in the case statement.
For instance, if I input a '1', the menu will recognize I input a 1 and will display the menu again with "You entered 1". instead of calling dec.getDec(), as it should according to the case statement. Any helpful hints or advice would be appreciated. This is a homework assignment, and I am not trying to get someone to write the code for me or anything. I just need to be pointed in the right direction please.
import java.io.IOException;
import java.io.*;
import java.util.Scanner;
public class Menu {
Scanner scan = new Scanner(System.in);
int selection;
public int GetSelection()
{
selection = scan.nextInt();
return selection;
}
public void display()
{
System.out.println("Please choose an option from the following:");
System.out.println("[1] Convert Decimal to Binary");
System.out.println("[2] Convert Decimal to Hexadecimal");
System.out.println("[3] Convert Binary to Decimal");
System.out.println("[4] Convert Binary to Hexadecimal");
System.out.println("[5] Convert Hexadecimal to Decimal");
System.out.println("[6] Convert Hexadecimal to Binary");
System.out.println("[0] Exit");
System.out.println("\n");
System.out.println("You entered: " + selection);
}
}
----------------------------
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)throws IOException {
LineWriter lw = new LineWriter("csis.txt");
int selection;
Decimal dec = new Decimal();
Binary bin = new Binary();
Hexadecimal hex = new Hexadecimal();
Menu menu = new Menu();
do{
menu.display();
selection=menu.GetSelection();
switch (selection){
case '1':{ dec.getDec();
break;}
case '2':{ dec.getHex();
break;}
case '3':{ bin.getBin();
break;}
case '4':{ bin.getHex();
break;}
case '5':{ hex.getHex();
break;}
case '6': { hex.getDec();
break; }
//default: System.out.println("Error: Unrecognized Selection");
// break;
}
}while (selection !=0);
}
}
As this is homework, I won't give you the whole solution, but I'll help get you there...
Your problem is coming from your use of Scanner, the helpful part of this page is A scanning operation may block waiting for input.
Using that you should be able to see where the problem is, if you need more help comment on this answer and I'll see if there's more I can do.
Don't use case 'n':, just use case n. You don't need the single quote. Also have a look at this tutorial on Switch Statements in Java to get an idea of how to use this in your code.
The problem with your current implementation is because you're trying to compare an int value (that you've in your selection variable) with char (which is internally getting converted to its corresponding int value i.e. int value of '1' is not the same as 1).
You can see the difference with the following code:
switch(selection){
case '1':
System.out.println("Hello World from char");
break;
case 1:
System.out.println("Hello World from int");
break;
}
So when you set selection = 1, you would find the output from the int block however if you set selection = '1', you would find the output from the char block
Note that I'm assuming that you're not running in Java 7
Note: There's another issue with your code. #Shaded has given you the perfect hint. Think about it with reference to how your control flows through your logic for setting the value of selection variable.

Switch Statement is making the first case skip a line

So I'm guessing that the solution to this is going to be really simple but I have no idea what I'm looking for so I'd like some help. What happens is that when I run the program, and choose case 1. It prints both "dog's name" and "dogs race" without giving me a chance to fill in the dogs name. So when I choose case 1 I start out only getting to fill in dogs race, how heavy, and how old it is! here is the code I'm using...
do {
System.out.println("(1 - reg\n2 - tail\n3- delete\n4-exit\nEnter number: ");
// so this is where the switch stuff starts
int option=sc.nextInt();
switch (option) {
case 1: System.out.println("Dog's Name: ");
String na=sc.nextLine();
System.out.println("Dog Race: ");
String ra=sc.nextLine();
System.out.println("How heavy?");
double wey=sc.nextDouble();
System.out.println("How old?");
double ag=sc.nextDouble();
dog doggy= new dog(na, ra, wey, ag);
kennel.add(doggy);
break;
case 2: System.out.println("its a tail");
break;
case 3: System.out.println("you delete");
break;
case 4: System.out.println("QUITTING\n(Data was not saved srry.)");
play = false;
default: System.out.println("try again");
}
}while(play);
I believe you need to call nextLine() after your call to nextInt(), because that hasn't advanced the scanner to the next line yet.
There's a newline reminder from your first sc.nextInt, you can change the delimiter to \n or just call nextLine(); just after reading the option (Using sc.useDelimiter("\n") )
Try:
int option=Integer.parseInt(sc.nextLine());
This has both the effect of advancing the cursor to the next line and getting the typed number.

Creating a console menu for user to make a selection

Doing a program in Eclipse with Java. What I want to do is when I execute the program I want present the user with a choice. I have all the calculations etc. done, I'm just unsure as to how to make this menu to offer the user choices. Example of what I'm looking for:
To enter an original number: Press 1
To encrypt a number: Press 2
To decrypt a number: Press 3
To quit: Press 4
Enter choice:
public static void main(String[] args) {
Data data = new Data();
data.menu(); }
}
For simplicity's sake I would recommend using a static method that returns an integer value of the option.
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
/***************************************************/
System.out.println("Choose from these choices");
System.out.println("-------------------------\n");
System.out.println("1 - Enter an original number");
System.out.println("2 - Encrypt a number");
System.out.println("3 - Decrypt a number");
System.out.println("4 - Quit");
selection = input.nextInt();
return selection;
}
Once you have the method complete you would display it accordingly in your main method as follows:
public static void main(String[] args) {
int userChoice;
/*********************************************************/
userChoice = menu();
//from here you can either use a switch statement on the userchoice
//or you use a while loop (while userChoice != the fourth selection)
//using if/else statements to do your actually functions for your choices.
}
hope this helps.
You can use a scanner to read input from System.in, as follows:
public static void main(String[] args) {
Data data = new Data();
data.menu();
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
// Perform "original number" case.
break;
case 2:
// Perform "encrypt number" case.
break;
case 3:
// Perform "decrypt number" case.
break;
case 4:
// Perform "quit" case.
break;
default:
// The user input an unexpected choice.
}
}
Note that this will require the user to input a number and press enter, before continuing execution. If they enter invalid input, this will halt; if you want it to prompt them again, you will need to wrap this in a loop of some sort, depending on how you want the system to behave.
Scanner#nextInt may very well throw an exception, should the user input something that cannot be parsed to an integer. You can catch this exception and handle it appropriately. If the user enters an integer that is out of the range of valid options (i.e. it is not in the range of 1-4), it will fall to the default branch of the switch statement, where you can again handle the error case however you wish.

Categories

Resources