More Trouble with 'do while' loops, Java - java

How do I get my program to prompt the user for different choices until they decide to purposefully exit the program? Right now I tried a do-while loop with a boolean called 'exit,' trying to say that while exit is false keep prompting the user to choose what to do, though all it does is ask them once and after it has done what the user wanted, the application stops.
Here is my code:
boolean exit = false;
do {
int options = 0;
do {
options = Integer.parseInt(JOptionPane.showInputDialog(null,
"Would you like to:"
+ "\n(Enter number value of option you would like to choose.)\n"
+ "\n1. See your recommendations. \n2. See top rated books."
+ "\n3. See random books of the day. \n4. Exit"));
} while (logIn < 1 || logIn > 4);
if (options == 1) {
recommend.displayRecommendations(custIndex);
} else if (options == 2) {
calculations.displayTopTen();
} else if (options == 3) {
calculations.displayRandomBooks();
} else if (options == 4) {
exit = true;
System.exit(0);
}
} while (exit = false);
Any help would be appreciated.

this be your problem:
while (exit = false);
Look very carefully...

You are checking a logIn variable but the correct one should be options. Change:
while (logIn < 1 || logIn > 4)
to:
while (options < 1 || options > 4)
In addition, the while (exit = false) (attempted assignment) must be while (exit == false) (comparison) or, even better, while (!exit)
And, lastly, though it doesn't matter that much, it's a bit superfluous to set exit = true immediately before calling System.exit().

Related

Why does my first input run through the do while even thought the input is 0

I am doing a school program about Casino App. First of all it is alright, but then I find out that something goes wrong with my first input. It is weird that only the first input goes wrong, others are fine. I am wondering what causes that happen and why?
public class test1
{
public static Scanner input;
public static void main(String[] args)
{
int winnings;
int bet = getBet();
do
{
TripleString thePull = pull();
getPayMultiplier(thePull);
winnings = bet * getPayMultiplier(thePull);
display(thePull, winnings);
bet =getBet();
}
while(bet != 0);
System.out.print("Thank you!");
}
public static int getBet()
{
final double MAX_BET = 50;
final double MIN_BET = 0 ;
String prompt, userResponse;
int Response;
do
{
prompt = "How much would you like to bet (1 - 50) or 0 to quit?";
System.out.print(prompt);
userResponse = input.nextLine();
Response = Integer.parseInt(userResponse);
}
while (Response < MIN_BET || Response > MAX_BET);
return Response;
}
My question is that when I put the first input as 0 (bet !=0 ) it shows :
How much would you like to bet (1 - 50) or 0 to
quit? 0
whirrrrrr .... and your pull is ...
BAR BAR BAR
Sorry, you lose.
How much would you like to bet (1 - 50) or 0 to
quit?
which is wrong. it should quit immediately, but if I put 0 anywhere except the first input, it works:
How much would you like to bet (1 - 50) or 0 to
quit? 1
whirrrrrr .... and your pull is ...
7 BAR cherries
Sorry, you lose.
How much would you like to bet (1 - 50) or 0 to quit? 0
Thanks for coming to Casino Loceff
Why is that?
Because do-while loop will run through the loop at least once and check the breaking condition only at the end. If you don’t want that behavior swap it for a normal while loop.
while(condition) { // your statements }
Because Response is 0. And that is not less than MIN_BET (which is 0), so the loop doesn't repeat.
Change it to <= MIN_BET, or (probably better), change MIN_BET to 1.
The problem is the usage of a do-while loop. The purpose of a do-while is to ensure the code block will always execute at least once.
The difference between a regular while and a do-while is when the expression is evaluated.
In a regular while loop the expression is checked before each loop starts. "Should I run the code?". This means that if the expression is false it will never run the block even once.
Whereas with a do-while the expression is checked after the code block executes - "Should I do this again?". So even if the expression is false the code block will be executed the first time.
Try using a regular while loop instead of do-while.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Your issue is most likely here
public static int getBet()
{
final double MAX_BET = 50;
final double MIN_BET = 1;//this should be 1 since you're asking for users to enter 1-50
String prompt, userResponse;
int Response;
do
{
prompt = "How much would you like to bet (1 - 50) or 0 to quit?";
System.out.print(prompt);
userResponse = input.nextLine();
Response = Integer.parseInt(userResponse);
//simplest way is just to add a condition here with an if statement to break the loop if the user enters 0
if(userResponse == 0){
break;
}
}
while (Response >= MIN_BET && Response <= MAX_BET);
return Response;
}

Can I use IF statements with a message dialog in java?

So, I've been stumped on this piece of code for about a week now, I want to have the code sending an error message when the user chooses 'No' or 'Cancel' however I get an error which tells me that NO and CANCEL are not variables. Does anyone have any suggestions as to how I can overcome this problem?
int mc = JOptionPane.QUESTION_MESSAGE;
int bc = JOptionPane.YES_NO_CANCEL_OPTION;
int ch = JOptionPane.showConfirmDialog (null, "Select:", "Title", bc, mc);
if (bc == NO)
{
JOptionPane.showInputDialog("Sorry, you cannot continue without agreeing to the rules.");
}
else if (bc == CANCEL)
{
JOptionPane.showInputDialog("Sorry, you cannot continue without agreeing to the rules.");
}
else
{
JOptionPane.showInputDialog("Thank you, you may continue!");
}
This is all explained in the JOptionPane Javadoc.
In the code that you've given, the button that you've clicked is identified by the return value from showConfirmDialog, which you've assigned to ch, not bc. In your case, the logic should be
if (ch == JOptionPane.NO_OPTION) {
...
}
else if (ch == JOptionPane.CANCEL_OPTION) {
...
}
else {
...
}

IndexOutOf range exception thrown in TimeHandler

I'm making a card-like game. The method below handles the opponents' attacks. It is supposed to go through the opponents' cards (with a two second delay between them) and execute their attacks (dealDamage() returns the damage). First it should check if the current opponent is active (i.e. not killed) and if it has already attacked, if so, their attack is executed. After that, the method moved to the next active opponent. After the last one it should stop iterating and change to the next round. Although the in first round everything goes as planned, but then it often crashes during the second or last round (when only one opponent is active). There can be 5 opponents max. I am clearly missing some obvious thing, but I can't get this to work.
EDIT
The error is in while(gm.opponentList.get(i).is available...
it is for examle index out of range: index 4 size 4.
public void opponentAttack(){
this.registerUpdateHandler(new TimerHandler(2f, true, new ITimerCallback() {
int i = 0;
#Override
public void onTimePassed(TimerHandler pTimerHandler) {
if (i < gm.opponentList.size()) {
while (gm.opponentList.get(i).isAvailable == false
|| gm.opponentList.get(i).attacked == true) {
i++;
}
if (gm.opponentList.get(i).isAvailable == true
&& gm.opponentList.get(i).attacked == false) {
gm.negotiationStrength = gm.negotiationStrength - gm.opponentList.get(i).dealDamage();
i++;
}
if (gm.negotiationStrength < 1) {
gm.negotiationEnded = true;
gm.playersTurn = false;
}
i = 0;
}else{
pTimerHandler.setAutoReset(false);
}
}
}));
gm.nextRound();
}
while (gm.opponentList.get(i).isAvailable == false
|| gm.opponentList.get(i).attacked == true) {
i++;
}
if the exit condition is never met, you keep incrementing i, and when it exceed the size of gm.opponentList throws an IndexOutBoundExcetion. You probably want to check i against gm.opponentList.size(), in the while loop

Trouble with creating Battleship using Java

The following block of code is supposed to check if the coordinates that the user entered are the coordinates of the ship. The ship is located on a two dimensional array at (1,1) and (1,2).
The problem started when I surrounded the getUserGuess method implementation with a while loop. The loop checks if the ship is still alive and will keep asking for the user to enter coordinates until the ship is sunk. However, as soon as the user enters either pair of the correct coordinates, the entire ship is sunk.
I have no idea why this keeps happening. As soon as I comment out the loop, the problem stops, but the loop is necessary.
Here is the method:
public void checkResult(String userGuess) {
while (frigateIsAlive == true) {
if (userGuess.equalsIgnoreCase(board[1][1])){
System.out.println("hit!");
numOfHitsOnFrigate++;
board[1][1] = " *";
createBoard();
}
if (userGuess.equalsIgnoreCase(board[1][2])) {
System.out.println("hit!");
numOfHitsOnFrigate++;
board[1][2] = " *";
createBoard();
}
else if (numOfHitsOnFrigate == 2) {
System.out.println("Enemy frigate has been sunk!");
frigateIsAlive = false;
break;
}
else {
System.out.println("miss!");
// try again
}
}
}
public String getUserGuess()
{ // takes the users guess
System.out.println("Choose a coordinate on the board to fire at");
int x = input.nextInt();
int y = input.nextInt();
String userGuess = board[x][y];
return userGuess;
}
Let me know if you need to see any other part of the code in order to better assist me.
This method is flawed :
If userGuess matches board[1][1], the loop will make you increment numOfHitsOnFrigate twice, and then you'll change frigateIsAlive to false and exit.
If userGuess matches board[1][2], the loop will make you increment numOfHitsOnFrigate infinite times and you'll never exit.
If userGuess doesn't match, the loop will never terminate, and keep printing miss! without getting new input.
You need to remove the loop, since this method checks a single userGuess, and change the conditions :
public void checkResult(String userGuess) {
if (userGuess.equalsIgnoreCase(board[1][1])){
System.out.println("hit!");
numOfHitsOnFrigate++;
board[1][1] = " *";
createBoard();
} else if (userGuess.equalsIgnoreCase(board[1][2])) {
System.out.println("hit!");
numOfHitsOnFrigate++;
board[1][2] = " *";
createBoard();
} else {
System.out.println("miss!");
// try again
}
if (numOfHitsOnFrigate == 2) {
System.out.println("Enemy frigate has been sunk!");
frigateIsAlive = false;
}
}
Based on what you wrote - I surrounded the getUserGuess method implementation with a while loop. - you have another loop which keeps getting input from the user. That other loop, whose code you haven't shown us, is necessary, since without it the game won't progress.
What you probably want (pseudo-code):
start (of a loop)
ask user for a guess
check result for the guess
sunk => stop / not sunk => continue to start
(i.e. you misplaced your while loop)

Validating a user's String type 'menu choice'

An assignment we were given recently had us building a basic, console-based, 'Tax Calculator', as it is something that got us to implement the things we'd learnt so far - variables, constants, loops etc.
One part of it had us present the user with a menu, where they would enter a letter - be it a,b,c,d or x - depending on what they wanted to do next.
That was no drama, as our assignment didn't ask for us to account for what happened if a user entered a choice not on the menu.
Now, for my own personal interest, I went back to it today, wanting to put some validation in there.
I defined the 'menuChoiceRule':
(menuChoice being a String)
boolean menuChoiceRule = (menuChoice.equalsIgnoreCase("A"))
|| (menuChoice.equalsIgnoreCase("B"))
|| (menuChoice.equalsIgnoreCase("C"))
|| (menuChoice.equalsIgnoreCase("D"))
|| (menuChoice.equalsIgnoreCase("X"));
And here is what should happen for as long as the rule is being broken: (The program should keep asking until it gets something that is in keeping with the rule, and then stop asking)
while (menuChoiceRule == false) {
System.out.print(menuChoiceString);
System.out.print("Enter Your Selection");
menuChoice = SCANNER.nextLine();
}
And what happens if the user is doing the right thing:
// As long as the user input is 'A','B','C' or 'D', they'll be able to
// keep doing stuff.
while (menuChoiceRule == true) {
*All the various menu options go here*
}
At the moment the while(menuChoiceRule == true) block (is that the right term?) works fine but while(menuChoiceRule == false) does not; Once the user inputs something that is in violation of the menuChoiceRule, the loop repeats endlessly no matter what is input (inputted?)
If someone could provide some insight as to why I'm having trouble here, it'd be much appreciated.
Regards,
AUS_Doug.
Looks like the boolean test is not being changed within the loop, place the code again at the bottom of the while loop.
Also, boolean tests do not need the ==, while(menuChoiceRule){ ... is the preferred coding style.
I would also consider creating a method to test for your rule:
private boolean testChoice(String menuChoice) {
return ((menuChoice.equalsIgnoreCase("A"))
|| (menuChoice.equalsIgnoreCase("B"))
|| (menuChoice.equalsIgnoreCase("C"))
|| (menuChoice.equalsIgnoreCase("D"))
|| (menuChoice.equalsIgnoreCase("X")));
}
This would give rise to the code:
boolean validChoice = false;
while (!validChoice) {
System.out.print(menuChoiceString);
System.out.print("Enter Your Selection");
menuChoice = SCANNER.nextLine();
validChoice = testChoice(menuChoice);
}

Categories