java loop logic issue - java

This feed method is supposed to first increase the energy state and decrease hungry state, use a dumplings meal (which can be purchased in the shop) then see that the item purchased from the shop, is a positive number or greater than 0. Then ensure that hungry and energy states do not go out of bounds (if it does print warning statements).
If it reaches the border of 100 then start increment overfeed, every time method is executed, if overfeed is greater than 4 then execute die method().
If it meets criteria running feed method will print Eating... and I have ate enough(...) statements.
#Override
protected void feed() {
decHungry(10);
incEnergy(10);
shop.useDumplingsMEAL();
do {
if (shop.dumplingsMEAL <= 0) {
JOptionPane.showMessageDialog(null, "You cannot eat right now, You need to purchase item in the shop");
}
else if (hungry <= 0 && energy >= 100) {
System.out.print("\nI have ate enough! My hungry state is " + hungry +
" and my energy state is " + energy + "." );
overfeed++;
while (overfeed>4)
{
die();
System.out.println("You have overfed me.");
}
}
else {
System.out.println("\nEating...");
System.out.println("I've just ate dumplings, my current energy state is " + energy
+" and hungry state is " + hungry + ".");
overfeed = 0;
}
}

You are calling a method called feed. This method looks like it should feed once if it can when it's called. Get rid of all the loops. If you want to keep it, read on do..while loop.
if(no food){
// nothing to feed
} else if (hunger level 0 or below & energy 100 or more){ // by the way hunger level should never go below 0 and energy should never go over 100
// increment overfeed
if(overfeed more than 4) {
// die
}
} else {
// feed
}

Just like the error message says, the syntax for do while is:
do {
// Do stuff
} while(some condition);
Also you seem to have some conditions that won't do what you want.

You are either having problem with your braces {} and indentation or don't understand properly how to use do-while loop.
Do-while should look like following:
do{
//making stuff
}
while(condition of loop);
At the moment your code looks like following:
do{
if(){
}
else{
while{
}
}
}

Related

Function not ending correctly after recursive loop

I am trying to build a copy cat of the game risk. I have a while loop which says while the attack isn't finished do something. Then I ask the user to type in either 'end turn' to end turn or 'continue' to recursively call the attack function again. The problem is after the user types in attack a few times and then 'end turn' the turn doesn't end rather it starts from the beginning or the function again. I would greatly appreciate an expert eye to look at my code and see what I am missing, thanks in advance.
public void attackOrSkip(Player player,Player[] playerArray, int playerId) {
boolean attackFinished = false;
int numUnitsAttackWith = 0;
int defenceArmiesNumber =0;
displayString(makeLongName(player) + ": Type 'attack' to attack or 'skip' to skip your turn...");
String command = commandPanel.getCommand();
displayString(PROMPT + command);
if(command.equals("skip") ||command.equals("skip ") ||command.equals("s")) {
return;
}else if (command.equals("attack") ||command.equals("attack ")){
displayString(PROMPT + command);
//while the attack isn't finished
while(attackFinished == false) {
//get the country the user is attacking
int countryAttackingFrom=countryFromCheck(playerId,player);
//get the country to attack
int countryToAttack = countryToCheck(player);
//get the player who we are attacking
int occupierPlayer =board.getOccupier(countryToAttack);
if ((board.getNumUnits(countryAttackingFrom)) < 2) {
displayString("You dont have enough units on this country to make an attack!");
attackOrSkip(player, playerArray, playerId);
break;
}
//if the country is adjacent to another one then you can attack else no
else if(isAdjacent(countryAttackingFrom,countryToAttack)) {
//check the number of unit to attack with
numUnitsAttackWith =numUnitsCheckerAttack(player,countryAttackingFrom);
//check the number of unit to defend with
defenceArmiesNumber = numUnitsCheckerDefence(player,countryToAttack);
//roll the dice
player.rollDice(numUnitsAttackWith);
playerArray[occupierPlayer].rollDice(defenceArmiesNumber);
//display the roll results
displayString(makeLongName(player) + "Rolled: "+printDie(player));
displayString(makeLongName(playerArray[occupierPlayer]) + "Rolled: "+printDie(playerArray[occupierPlayer]));
}
displayString(makeLongName(player) + ": 'end turn' or 'continue'");
command = commandPanel.getCommand();
displayString(PROMPT + command);
if(command.equals("end turn")||command.equals("end turn ") ||command.equals("endturn")||command.equals("endturn ") ||command.equals("end")) {
attackFinished = true;
return;
}else if(command.equals("attack") ||command.equals("attack ")){
// break;
}else if(command.equals("continue") ||command.equals("continue ") ||command.equals("con")){
attackOrSkip(player,playerArray,playerId);
}else {
return;
}
}else {
displayString(makeLongName(player) + ": ERROR, not adjacent countries");
}
}
}
}
Okay - as currently written - every time you call attackOrSkip within the method - you end up 1 level lower in the stack - with a new set of variables -
attackFinished, numUnitsAttackWith, defenceArmiesNumber
When you leave the recursion (i.e. via a return) you end up with simple variables as they were before you enter the recursive call - remember Java is Call By Value (even though you can pass in references to objects, you get a value (the current value of the variable reference when called ... and changing the reference to point at a different object doesn't change the callers reference).
SO, without looking to see whether you have done the correct algorithm - I would guess that if you made the method return type a boolean and returned the status instead of nothing, you could update attackFinished and the right thing might happen..
e.g. change all the
return;
to
return attackFinished;
AND change all the places where you call
attackOrSkip(....)
to set attack finished based on what the method return
attackFinished = attackOrSkip(....)
OR - you can pass in an extra parameter - attackFinished - in a Holder (an example of the concept) object - again the reference can't change, but you can go attackFinished.value = true (and it will then be the same the whole way out the stack as you drop out of the recursion).

Need Help! Number Wizard in java?

I was just trying to get NumberWizard to work on java and I couldn't quite get it. Or can you just not do it in java? I'm pretty stuck because I can only get it to guess one time.
I'm using Processing 3 and my code looks like this:
int max = 1000, min = 1, guess = 500;
void setup() {
size(400, 400);
background(0);
println("welcome to NumberGuesser ");
println("In this game you're gonna think of a ");
println("number and im gonna guess it as fast as possible ");
println(" \n ");
println("Now pick of a number between " + min + "and" + max);
println("Great! now that you have picked a number ");
println("Press the up-arrow if its more");
println("and the down-arrow if it's less ");
println("is it less or more than "+ guess + "? \nif more press up-arrow, if less press down-arrow");
}
void draw() {
if (key == CODED) {
if (keyCode == 38) { // up-arrow
min = guess;
nextGuess();
} else if (keyCode == 40) { //down-arrow
max = guess;
nextGuess();
} else if (keyCode == 13) { //return
win();
}
}
}
void nextGuess() {
frameRate(1);
guess = (max + min) /2;
println("Is it less or more than "+ guess + "? \nif more press up-arrow, if less press down-arrow ");
}
void win() {
println("that was'nt hard at all, ezz pezz! ");
noLoop();
}
Please note that the draw() function fires 60 times per second. Even after you call frameRate(1), the draw() function fires once per second. Further note that all of your logic is inside your draw() function. So the guessing will happen on an interval.
You're also not checking whether the key is currently pressed. Note that the key and keyCode variables contain the most recently pressed key. You still need to check whether the key is currently pressed. You can use the keyPressed variable or the keyPressed() function for this.
If I were you, I'd modify my program to use the keyPressed() function to detect user input instead of polling for it in the draw() function.
Also, you need to get in the habit of debugging your code. Try to isolate the problem to a specific line of code that's behaving differently from what you expected, instead of posting your full program and saying it's not working.

Java if...else statement not working properly

public double transferSavingToChecking(double Tamount2)
{
//check if enough to transfer
if(Tamount2 > Saving_Balance)
System.out.println("Transfer failed. You don't have enough balance in the saving account!");
else
System.out.println("You have successfully transferred $" + Tamount2 + " from the saving account to the checking account");
Saving_Balance = Saving_Balance - Tamount2;
Checking_Balance = Checking_Balance + Tamount2;
return Checking_Balance;
}
When money is transferred, the if...else statement runs through every time. For example, even when the transfer > balance, the output reflects that the transfer occurred anyways even when it says it failed.
You need to put curly braces around the content of your if/else blocks. If/else statements are written in the following way:
if (condition) {
// do something
} else {
// do something else
}
If you miss out the curly braces, only the first statement after the if/else is considered part of the if/else block.
Change your code to the following:
public double transferSavingToChecking(double Tamount2) {
//check if enough to transfer
if(Tamount2 > Saving_Balance) {
System.out.println("Transfer failed. You don't have enough balance in the saving account!");
} else {
System.out.println("You have successfully transferred $" + Tamount2 + " from the saving account to the checking account");
Saving_Balance=Saving_Balance - Tamount2;
Checking_Balance=Checking_Balance + Tamount2;
}
return Checking_Balance;
}

How to make a proper if-else statement given multiple rules to run the program

Hello i need to invent a baccarat game.. now on top of that there are rules given that i need to follow to make the game successful. the problem is im getting confused with my if-else statement. Idk which should come first. and which shouldnt. sometimes when i run it it looks good but when i run it several times with different random numbers being produced, it seems like none of my if-else statement works( under the //rules section). Please help!
EDITED:(new //rules)
//rules
if(sumPlayer > 7 && sumPlayer <10) {
System.out.println ( " Natural! No cards are drawn. ");
} else if (sumPlayer <6){
System.out.println ( " Player must draw to a hand of 5 or less." +
"\nPlayer draws a third card: " +c3+ " .");
} else if(c3 > 5){
System.out.println ( " Player stands a pat. ");
} else {
System.out.println ( " Player's hand is now : " +sumC3+ " .");
}
You want to deal with the player and dealer's hands separately. In a series of if/else decisions, only one branch can ever be selected. This means the conditions tested inside a set of if/else statements should be mutually exclusive. If you test conditions of your hand, and then the dealers hand, those two conditions may both be possible at the same time, but if/then code can't handle both.
Here's some pseudocode that illustrates this:
if(test my hand 1) {
do something with my score
} else if(test my hand 2){
do something with my score
} else if(test my hand 3){
do something with my score
} else {
do a default thing with my score
}
if(test dealer hand 1) {
do something with dealer score
} else if(test dealer hand 2){
do something with dealer score
} else if(test dealer hand 3){
do something with dealer score
} else {
do a default thing with dealer score
}
By the way - when you show which player wins, you might want to show the score too. It's good for debugging and also nice to let the user know how well they played.

Java TicTacToe - comparing lots of values

I am writing this TicTacToe game. We all know how TicTacToe works, either somebody wins or nobody wins and the board gets full.
board.playable() checks to see if somebody has won the game or if the board is full. This code runs fine but I'm just wondering if there is a tidier way to write my while loop. It just seems a bit redundant to have the same condition twice. But I need to run the board.playable() check before the computer makes his move.
public void runGame()
{
while(board.playable()==true)
{
// Outputs a visual representation to console window
this.displayBoard();
// Asks player to enter a valid number
this.playerMove();
// Check if it still playable for the next
if(board.playable() == true)
{
computerMove()
}
}
this.displayBoard();
// Outputs the final status of the game and the winner if any
if(board.wonBoard()==true) {
System.out.println(board.whoWon() + " has won the game");
} else {
System.out.println("The board is full. Nobody has won the game");
}
}
Your program doesn't seem to have a "turn" state. If it had such an entity, then it could play a turn and check for winner after each turn. Also, get rid of == true in all of your code.
while (gameNotOver) {
// assuming an enum called Turn
if (turn == Turn.PLAYER) {
doPlayersTurn();
} else {
doComputerTurn();
}
checkForWin();
turn = turn.nextTurn();
}
while(board.playable())
{
// Outputs a visual representation to console window
this.displayBoard();
// Asks player to enter a valid number
this.playerMove();
// Check if it still playable for the next
if(board.playable())
{
computerMove();
}
}
remove ==true
You can use the flag to know whose move is : Like this
boolean playerTurn = Boolean.TRUE;
while(board.playable()==true)
{
// Outputs a visual representation to console window
this.displayBoard();
// Asks player to enter a valid number
if(playerTurn){
this.playerMove();
playerTurn=Boolean.FALSE;
}
else{
computerMove();
playerTurn = Boolean.TRUE;
}
}

Categories

Resources