by pass do while loop - java

I wondering is it possible to skip past a do while loop or even exit a method halfway through it if certain conditions are met?
Heres an example of what I mean ( everything works in this )
public void loanBook() {
Scanner input = new Scanner(System.in);
boolean successful = false;
boolean bookExists = false;
boolean memberIDExists = false;
boolean memberCurrentlyLoaningBook = false;
int memberID = 0;
System.out.println("You must be a member of the library to loan out a book");
do {
System.out.println("\nPlease enter your memberID (Press 9 to exit)");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
}
memberID = input.nextInt();
for (int i = 0; i < members.size(); i++) {
if (memberID == members.get(i).getMemberID()) {
memberIDExists=true;
if(members.get(i).isCurrentlyLoaningBook()==false){
successful = true;
memberCurrentlyLoaningBook=true;
}
}
}
if(!memberCurrentlyLoaningBook){
System.out.println("This member is currently loaning a book");
}
if (!memberIDExists) {
System.out.println("This member ID does not exist");
}
} while (successful == false);
EDIT
do while loops that are in the same method
do { these other do while loops are after this first one and do other things
} while (); ( I haven't included what they do as it takes up too
do { much space)
} while();
I have an option here to exit to the main menu, but i also have a do while loop after this, so whenever I enter 9 it just exits the current to while loop and goes on to the next one, is there anyway that I can skip past all the proceeding do while loops after I press 9, or even exit the method?

In your case continueor breakcould be useful. But if you want to exit the method you could just do it with return.

Try this, I have added break; when user enter "9" as an input. It will then come out of the do while loop.
do {
System.out.println("\nPlease enter your memberID (Press 9 to exit)");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
break;
}
EDIT:
Yes to Check for the next loop, add a condition with that loop
loop(your original condition && !successful)
{
}
EDIT 2:
TO come out of the loop and avoid other do while loops in the method, you can just return;
It will take back the control of the program through which this method was called.
do {
System.out.println("\nPlease enter your memberID (Press 9 to exit)");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
return;
}

Related

While loop NoSuchElementException integer input java

I'm having some trouble with a menu program I am writing for my java class. After one program is run, when the program goes to do a second loop it throws a NoSuchElementException on the line where it is supposed to take the user's input for the next program they want to run. I'm assuming it has something to do with the scanner getting messed up but I can't find the issue. Anyone have any ideas?
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String pin;
int selection = 0;
boolean valid = false;
do {
System.out.print("Please enter the password: ");
pin = console.nextLine();
valid = checkPassword(pin);
} while (!valid);
while (selection != 4 && valid == true) {
System.out.printf("%nPlease select a number from the menu below %n1: Wage "
+ "Calculator 2: Tip Calculator 3: Grocery Discount 4: Exit %n");
selection = console.nextInt();
if (selection == 1) {
calc_wages();
} else if (selection == 2) {
calc_tip();
} else if (selection == 3) {
System.out.print("We haven't gotten this far yet");
} else if (selection == 4){
System.out.print("Thank you for using the program.");
break;
} else {
System.out.print("There is no option for what you entered. Try again");
}
selection = 0;
}
}//main
Your code so far is fine.
From what you're saying the problem starts after the user makes a selection.
In calc_wages() and/or calc_tip() it's possible that you use another Scanner object to get the user's input.
This is a source of problems.
Declare 1 Scanner object at the class level and use it throughout you code and close it only when it is no longer needed.

Restarting my game skips every Scanner class and loops? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I'm currently making a Tic Tac Toe game. when a player wins and is asked if they want to play again, I call the Playing(); method to restart the game. The issue I'm having is that it loops the Playing(); without stopping at the first Scanner.
How can I make the loop stop at the first Scanner (which asks the user to enter their [row]?
Output when A player agrees to restart :
Enter [Row] : Please enter a number :
Enter [Row] :
Playing() Method
public static void Playing() {
String line;
// Check if the user's input is a number. If not, retry!
while (true) {
try {
System.out.print("\nEnter [Row] : "); //Tell user to input Row
line = input.nextLine();
row = Integer.parseInt(line) - 1;
System.out.print("Enter [Col] : "); //Tell user to input Col
line = input.nextLine();
col = Integer.parseInt(line) - 1;
break;
} catch (NumberFormatException e) {
System.out.print("Please enter a number : ");
break;
}
}
//Check if their input for [row][col] is valid
if (row < 0 || row > 2 || col < 0 || col > 2) {
System.out.print("Oops! Invalid input. Try again");
Playing();
} else if (Board[row][col] != '_') {
System.out.print("This position is already taken. Try again");
Playing();
} else {
Board[row][col] = player;
moveCount++;
DisplayBoard();
GameOver(); //Check if anyone won. If not, continue the game
}
}
Replay() Method
public static void Replay() {
/*
* Check if the user wants to play again
*/
System.out.print("Would you like to play again?(Y or N) : ");
while (true) {
String retry = input.next();
if ("y".equalsIgnoreCase(retry)) {
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
Board[r][c] = '_';
}
}
System.out.print("-----------------------------------------------------\n");
DisplayBoard();
Playing();
break;
} else if ("n".equalsIgnoreCase(retry)) {
System.out.println("Thank you for Playing!");
System.exit(1);
// If the user enters an invalid input, this will ask them to try again
} else {
System.out.print("Invalid input. Would you like to play again?(Y or N) : ");
}
}
}
First of all, what is the reason for using
line = input.nextLine();
row = Integer.parseInt(line) - 1;
where one can actually get the integers using nextInt() method available from Scanner
line = input.nextInt();
row = line - 1;
And to answer your question, I think this is the culprit which causes to skip your inputs
String retry = input.next();
In this line if your enter some keyword, say "Hello" and hit enter which is "Hello\n" the next method only takes "Hello" and the \n will skip your nextLine() method. So I suggest you to try adding another nextLine() after this line
String retry = input.next();
input.nextLine();
Note: This is only a guess for a problem, I haven't actually debugged your code by running on my end-system.

How to return to main menu when exit is inputted

I want to return to main menu aka "eventSelection" if 4 (exit) is selected. Right now I have it as return which exits whole program.
import java.util.*;
public class SchedulingProgram {
public static void main (String [] args) {
eventSelection();
}
public static void eventSelection() {
Scanner sc = new Scanner(System.in);
System.out.println("Select Scheduling Action");
System.out.print("Add an Event = 1. \nDisplay Events = 2.\nPrint Alert = 3. \nExit = 4. \nINPUT : ");
int actionSelect = sc.nextInt();
if (actionSelect >= 1 && actionSelect <= 4) {
if (actionSelect == 1) {
addEvent();
} else if (actionSelect == 2) {
displayEvent();
} else if (actionSelect == 3) {
printAlert();
} else if (actionSelect == 4) {
return;
}
} else {
System.out.println("Error : Choice " + actionSelect + " Does Not Exist.");
}
}
I used to play with these kind of things too when I first started learning Java.
The most simple solution is indeed a while-loop. It evaluates the boolean expression and keeps executing the code within its brackets for as long as the boolean equals 'true'.
I refactored your example:
public static void eventSelection() {
Scanner sc = new Scanner(System.in);
int actionSelect = 0;
while (actionSelect != 4) {
System.out.println("Select Scheduling Action");
System.out.print("Add an Event = 1. \nDisplay Events = 2.\nPrint Alert = 3. \nExit program = 4. \nINPUT : ");
actionSelect = sc.nextInt();
switch (actionSelect) {
case 1:
addEvent();
break;
case 2:
displayEvent();
break;
case 3:
printAlert();
break;
default:
break;
}
}
System.out.println("Exited program");
}
It will now display your menu everytime a number is entered. Except when they enter 4, which now becomes the exit out of your entire program.
When faced with multiple if-else, it's perhaps better to use a switch-case. It takes a parameter and per case, you can define the action.
If the entered parameter doesn't match a case, it falls back to the default (in this case, it does nothing and the program will continue, showing the select menu anyway)
The 'break' keyword is needed to contain the cases. Otherwise, the next line of code would be executed as well. A bit more information about the switch statement can be found here.
And ofcourse, here's the link to the while-loops.
One last tip... As I learned to program, I found that there's nothing more important than to (re)search as much as I could on Google. There are examples aplenty out there.

My try/catch keeps catching the correct information and re asking, but only once. In Java

// this is my code. It will only spit out that last bit of information (wallet and name) the second time i put in the players number
String option;
Boolean validChoice = false;
while(!validChoice){
option = gameScanner.nextLine();
try {
selectedPlayer = Integer.parseInt(option);
if (selectedPlayer<0|| selectedPlayer>playerNames.length) {
System.out.println("Invalid choice!: Please pick another number");
}else {
validChoice = true;
}
} catch(Exception ex){
selectedPlayer = -1;
System.out.println("Invalid choice!: Please pick another number");
}
}
System.out.println("");
System.out.println("PLAYER INFO");
System.out.println("Name: " + playerNames[selectedPlayer]);
System.out.println("Wallet: " + playerWallets[selectedPlayer]);
Problem : your if condition is not correct.as you are taking array index value as input(index always starts from 0) you should always check for both greater than or equal of length instead of only greater than of length of the array.
Reason for failure: assume your playerNames array contains 5 items means length = 5. so validChoid would be between 0 to 4 as array index starts from 0.
in the code as you have given wrong condition selectedPlayer>playerNames.length if the user enters 5(invalid) which will not satisfy above condition and then goes to else block setting the validChoice to true though it is invalid choice. as soon as validChoice becomes true it comes out from the while loop.
Solution: change the if condition from this :
if (selectedPlayer<0|| selectedPlayer>playerNames.length)
to this:
if (selectedPlayer<0 || selectedPlayer >= playerNames.length)
Complete Solution:
String option;
Boolean validChoice = false;
while(!validChoice){
option = gameScanner.nextLine();
try {
selectedPlayer = Integer.parseInt(option);
if (selectedPlayer<0 || selectedPlayer>=playerNames.length) {
System.out.println("Invalid choice!: Please pick another number");
}else {
validChoice = true;
}
} catch(Exception ex){
selectedPlayer = -1;
System.out.println("Invalid choice!: Please pick another number");
}
}
System.out.println("");
System.out.println("PLAYER INFO");
System.out.println("Name: " + playerNames[selectedPlayer]);
System.out.println("Wallet: " + playerWallets[selectedPlayer]);

How is it possible to update this method that it allows a user to only guess 5 times?

Is a do..while loop with an incremented counter how you would only allow user to guess 5 times? Attempted to do so with the do while but doesn't seem to work...
Or would a for loop be best way to do so?
public static void guessRandomNumber() {
// declare var for user guess and default to zero
int userGuess = 0;
// declare boolean relating to if number is valid
boolean validNumber = false;
// declare boolean relating to if guess is correct
boolean correctGuess = false;
// declaring int equal to return value from generateRandomNumber();
int secretNumber = generateRandomNumber();
//Do while loop that runs until user guesses correctly
do {
//Do while loop that runs until a valid entry is given (i.e. an integer)
do {
try {
//do while loop ensuring that user guess is between 1 and 10
do {
// Get user guess (between 1 and 10)
System.out.println("Please enter a number between 1 and 10...");
userGuess = scanner.nextInt();
if (userGuess < 1 || userGuess > 10) {
validNumber = false;
System.out.println("Please Ensure number is between 1 and 10");
}else {
validNumber=true;
}
} while (!validNumber);
} catch (Exception ex) {
//Print error message
System.out.println("Sorry invalid entry...");
// Flush scanner
scanner.next();
validNumber = false;
}
} while (!validNumber);
//If else statement that outputs a message informing user if guess correct
if (userGuess == secretNumber) {
System.out.println("Guess correct, well done!");
correctGuess = true;
} else {
System.out.println("Sorry guess Incorrect please try again!");
correctGuess = false;
}
} while (!correctGuess);
}// end ofGuessRandomNumber
just add a counter numberOfGuesses and change the while loop like this:
do {
// do stuff and increment numberOfGuesses
} while (!correctGuess && numberOfGuesses < 5);
Also I don't see why you would need 3 while loops for this task. One would be enough, you can check all conditions in one.
you can use a counter as follows and you can continue up to 5 and break after that.
int counter=1;
while(counter<=5){ // while loop will runs 5 times.
// do your task
counter++; // up your counter value.
}
You can have some idea from this.
Have a counter, which you decrement on each validNumber, and in the outer loop check that this is non zero.

Categories

Resources