Nested do while loop jump from one to another - java

I am having some logic difficulties when trying to use a do-while loop. In my main() method. I am trying to prompt user again and again if they entered anything larger than 6:
do{
System.out.println("select your option: ");
System.out.println("1.option1");
System.out.println("2.option2");
System.out.println("3.option3");
System.out.println("4.option4");
System.out.println("5.option5");
System.out.println("6.Quit");
optionChoice = sc.nextInt();
switch (optionChoice) {
case 1:
option1Method();
break;
}
} while (optionChoice > 6);
Then inside my option1Method(), I have another do while loop:
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.Back");
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
case 4: return;
default: break;
}
} while (optOption > 4);
For this method, I am trying to prompt user the choice again and again as long as they entered anything larger than 4. Then, when they entered 4, it should go back to the do while loop in main() method.
However, for the second do-while loop, when I entered 4, the program itself is just terminated. Any ideas?
Thanks in advance.

In the main method set the condition as:
optionChoice != 6

I am not sure if this is what you want, but I have written the following for you:
import java.util.Scanner;
public class Answer {
static Scanner sc = new Scanner(System.in);
static int optionChoice;
public static void main(String[] args) {
do{
System.out.println("select your option: ");
System.out.println("1.option1");
System.out.println("2.option2");
System.out.println("3.option3");
System.out.println("4.option4");
System.out.println("5.option5");
System.out.println("6.Quit");
optionChoice = sc.nextInt();
switch (optionChoice) {
case 1:
option1Method();
break;
}
} while (optionChoice > 6);
}
public static void option1Method() {
int optOption;
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.Back");
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
case 4:
optionChoice = 7; // you have to make this value greater than 6 if you want to continue in the loop
return;
default: break;
}
} while (optOption > 4);
}
}
The problem when you enter 4 is that you go back to the main method, and the value you entered for optionChoice is 1 which makes false the condition of the while loop.
EDIT:
In response to #Timeout who is totally right by claiming I am assuming that optionChoice is a "global variable".
To keep your functionality I guess you should just have the following condition in the do-while loop of the main() method:
optionChoice > 6 || optionChoice == 1
EDIT:
what if you add as a condition in the second while loop
optOption != 4
so that you will remain in that loop until the user enters 4
EDIT TO HANDLE optionXMethod where X is a number:
do{
System.out.println("select your option: ");
System.out.println("1.option1");
System.out.println("2.option2");
System.out.println("3.option3");
System.out.println("4.option4");
System.out.println("5.option5");
System.out.println("6.Quit")
optionChoice = sc.nextInt();
switch (optionChoice) {
case 1:
option1Method();
break;
case 2:
option2Method();
break;
case X:
optionXMethod();
break;
}
} while (optionChoice != 6);
void option1Method() {
int optOption;
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.Back");
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
// you do not need the case 4: because when optOptiontakes the value of 4 it leaves the loop
default: break;
}
} while (optOption != 4);
}
....
General case:
void optionXMethod() {
int optOption;
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.opt4 method4");
// more options
System.out.println("X.Back"); // where X is the number option of Back
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
// you do not need the case 4: because when optOptiontakes the value of 4 it leaves the loop
default: break;
}
} while (optOption != X); // whatever the value of X is should be consider for this condition
}

Related

An option in my do-while to print out all 3 conditions

String xdd="";
Scanner Lenijs = new Scanner(System.in);
do {
System.out.println("Starting number a: ");
int a = Lenijs.nextInt();
System.out.println("Ending number b: ");
int b = Lenijs.nextInt();
System.out.println("Choose 1.for a-b, 2. for all even and 3. for odd numbers.");
int c = Lenijs.nextInt();
if (c == 1) {
do{
System.out.println(a);
a++;
}while(a<=b);
}
if(c == 2) {
if(a%2==0) {
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
else {
a++;
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
}
if(c == 3) {
if(a%2==0) {
a++;
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
else {
do{
System.out.println(a);
a=a+2;
}while(a<=b);
}
}
System.out.println("Do you wish to continue? (Yes/No)");
xdd=Lenijs.next();
}while(xdd.equals("Yes"));
}
}
How could I add a 4th option where the user can print out all 3, as of now you can individually select from 1-3 where u get for 1.just from a-b all numbers, 2.is a-b with only pairs and 3.is a-b only odd, but I wanted a 4th option where u could get them all together and is easy to read/overview. Is that possible to make or it won't look good/can't with my code?
It is generally a good practice to limit a method to doing just one thing. So the method that decides which action to perform should not be performing the action - it passes responsibility to the appropriate method(s). In this case, move each activity into a separate method and use a switch to invoke each as appropriate. The following illustrates the concept.
switch(c) {
case 1:
do1();
break;
case 2:
do2();
break;
case 3:
do3();
break;
case 4:
do1();
do2();
do3();
break;
default:
reportUnknownEntry(c);
}

How to catch an Error in a Switch statement when the user entered number doesn't exist

I'm trying to error proof my program that basically works as a mini calculator. But I have no idea how to write a "Catch" statement that would detect when the user enters a case number that doesn't exist, in my case anything that is negative or > 4
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
}
}
catch(Exception e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
} ```
Why do you want to throw an Exception unnecessarily? I suggest you just put a default case in your switch with the required error message. Also, move the input part inside the loop, so that it continues to take input.
I also suggest you use nextLine() instead of nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = 0, n = 1;
boolean valid;
do {
do {
valid = true;
try {
operacija = Integer.parseInt(operacijai.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter an integer only.");
valid = false;
}
} while (!valid);
switch (operacija) {
case 1:
System.out.println("addingMethod()");
n = 2;
break;
case 2:
System.out.println("subtractingMethod()");
n = 2;
break;
case 3:
System.out.println("multiplyingMethod()");
n = 2;
break;
case 4:
System.out.println("dividingMethod()");
n = 2;
break;
default:
System.out.println("Invalid input");
}
} while (n == 1);
}
}
A sample run:
Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
5
Invalid input
Another sample run:
Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
a
Enter an integer only.
5
Invalid input
2
subtractingMethod()
You can also handle the use case in default
It is totally upto your use-case how you are handling the exception, you can also create your custom exception and throw from default
something like:
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
default:
System.out.print("Enter a correct number!")
throw new CustomException();
}
}
catch(CustomException e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
}
Figured out a clean way of doing this with default case.
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija;
do {
operacija = operacijai.nextInt();
switch (operacija) {
case 1:
addingMethod();
break;
case 2:
subtractingMethod();
break;
case 3:
multiplyingMethod();
break;
case 4:
dividingMethod();
break;
default:
System.out.print("Enter a correct number!");
}
} while(operacija < 1 || operacija > 4);
operacijai.close();
}

Java programming cant get my while statement to loop

I'm trying to get the user to give input and then after everything from all the cases was read out to them, re-loop to the output.displayMainMenu(); until they were to enter 4 to exit the program.
output.displayMainMenu();
int entry = keyboard.nextInt();
while(entry >= 1 || entry <=4) {
output.displayMainMenu();
switch(entry) {
case 1:
output.displayStockChoices(portfolio);
portfolio.editPostion();
portfolio.displayPositions();
break;
case 2:
portfolio.updateCurrentPrice();
break;
case 3:
System.out.print(investor.toString() + "Account Balance: " +portfolio.calcTotalAccountValue());
break;
case 4:
System.out.print("Done.");
break;
default:
System.out.print("please enter 1-4!");
}
break;
}
It's better to use a do-while loop because the code inside the loop need to be ran at least one time. I agree with #AntonH, that are several issues in this code. I rewrote it considering the mentioned issues.
int entry = 0;
do {
output.displayMainMenu();
try {
entry = keyboard.nextInt();
} catch (InputMismatchException e) {
System.out.print("Invalid input. ");
}
switch (entry) {
case 1:
output.displayStockChoices(portfolio);
portfolio.editPosition();
portfolio.displayPositions();
break;
case 2:
portfolio.updateCurrentPrice();
break;
case 3:
System.out.print(investor.toString() + "Account Balance: "
+ portfolio.calcTotalAccountValue());
break;
case 4:
System.out.print("Done.");
break;
default:
System.out.print("please enter 1-4!");
}
} while (entry >= 1 && entry < 4);
// Don't forget to close Scanner object when program finish
keyboard.close();

On Switch How to use logic operator on case JAVA

i have a problem i dont know what to put on case section, when ever the user input their grades from 0-100 there are output corresponds to their grades failed,good,verygood,excellent.
import java.util.Scanner;
public class ProgTestI {
public static void main (String args[]){
Scanner pao = new Scanner(System.in);
System.out.print("Grades: ");
String grades = pao.next();
int grado = Integer.parseInt(grades);
switch (grado){
case =<74: /* iwant to put 0 to 74*/
System.out.println("Failed");
case : /* 75-80*/
System.out.println("bellow average");
case : /*81-85*/
System.out.println("average");
case : /*86-90*/
System.out.println("Good");
case : /*91-96*/
System.out.println("VeryGood");
default:
}
}
}
You cannot use switch for ranges, you need to replace this chunk of code with proper if/else blocks.
Switch works only on numeric values, but it works like
if(numericVal == 40)
So writing it for ranges is... waste of code, and not readable.
You need to rewrite it:
if( g <= 74){
...
}else if( g > 74 && g <= 80 ){
...
Your case code is incorrect, you can do as Beri mentioned.
If you want to implement switch statement in your application, then you can do as follows:
public static void main(String[] args) {
Scanner pao = new Scanner(System.in);
System.out.print("Grades: ");
String grades = pao.next();
int grado = Integer.parseInt(grades);
int checkedCase=0;
if(grado<=74){
checkedCase=1;
}
else if(grado>=75&&grado<=80){
checkedCase=2;
}
else if(grado>=81&&grado<=85){
checkedCase=3;
}
else if(grado>=86&&grado<=90){
checkedCase=4;
}
else if(grado>=91&&grado<=96){
checkedCase=5;
}
switch (checkedCase){
case 1: /* iwant to put 0 to 74*/
System.out.println("Failed");
break;
case 2: /* 75-80*/
System.out.println("bellow average");
break;
case 3: /*81-85*/
System.out.println("average");
break;
case 4: /*86-90*/
System.out.println("Good");
break;
case 5: /*91-96*/
System.out.println("VeryGood");
break;
default: System.out.println("Please enter a value in range 0-96");
break;
}
}

How to return to main menu in switch case after executing a method?

How do I get get the menu to display again after the selected method executes?
I have the menu option print to the console. Then it takes user input (1 - 6), calls according method, and then should return to the menu for the user to select from the menu again.
After the selected method executes, the program just ends.
public static void main (String[] arg) {
Scanner kbd = new Scanner(System.in);
String mainMenu = ("Select a choice from the menu: \n"
+ "1. Add new DVD entry\n"
+ "2. Look Up DVD Entry\n"
+ "3. Display DVDs By Category\n"
+ "4. Remove DVD Entry\n"
+ "5. Save Data\n"
+ "6. Exit");
System.out.println(mainMenu);
menuChoice = kbd.nextInt();
while (menuChoice < 1 || menuChoice > 6) {
System.out.print("\nError! Incorrect choice.\n");
System.out.println(mainMenu);
menuChoice = kbd.nextInt();
}
switch (menuChoice) {
case 1: {
// method code
}
else {
// method code
return;
}
}
case 2: {
// method code
return;
}
case 3: {
// method code
return;
}
case 4: {
// method code
return;
}
case 5: {
// method code
return;
}
case 6: {
// method code
System.exit(0);
return;
}
}
}
Use a do while
do
{
System.out.println(mainMenu);
menuChoice = kbd.nextInt();
... switch/case ...
... remove the return statements from your cases.
} while (menuChoice != 6);
You also have to remove the return from your cases. Otherwise it will return out of main. Replace them with break;
This is how switch cases need to be
switch (menuChoice)
{
case 1:
Do what you want.
break;
case 2:
...
break;
default:
...
break;
}
You don't usually need { or if inside the switch case.
wrap your code inside
while(menuChoice != 6)
{
...
}

Categories