Why does nothing happen when a "if ... <=0" criteria is met? - java

I have a player controlled object which is set to 100 health. With each hit from an enemy it goes down. The problem is, after it reaches 0 health, it still keeps going further into the negatives. I have a popup set
private void playerHealth(){
if (player.health <= 0)
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
so that in theory, it should pop up after health is <=0. However, when I try to run it, it just opens and closes immediately. I can see the window for a split second. If I delete the
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
and replace it with say,
player.isAlive = false;
(isAlive is set true for player, enemies and all bullets), the health will continue to decrease past the negatives.
This part might help as well: Its the code to delete the dead enemies and bullets, there is nothing similar for player, so that may be the problem.
private void removeDead(){
for (int i = 0; i <bullets.size(); i++){
if (bullets.get(i).isAlive == false )
bullets.remove(i);
}
for (int i = 0; i <mobs.size(); i++){
if (mobs.get(i).isAlive == false )
mobs.remove(i);
}
for (int i = 0; i <mobBullets.size(); i++){
if (mobBullets.get(i).isAlive == false )
mobBullets.remove(i);
}
bullets.trimToSize();
mobs.trimToSize();
mobBullets.trimToSize();
}
So any help is appreciated. Thank you. (all the code is from an online tutorial, which is why I dont know anything.)

If you want both statements to be executed, surround them in a block :
private void playerHealth() {
if (player.health <= 0) {
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
}
Without the curly braces, System.exit(0); is not part of the if statement and will always be executed, which explains the it just opens and closes immediately.

I agree with the previous answer.
However, you need to know how to avoid such problems in the future. Use an IDE or other editor that will automatically indent your code for you. Here is what one did to the failing if-statement:
private void playerHealth() {
if (player.health <= 0)
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
The problem becomes much more obvious.

It looks like you missed a { on your if statement, if you want to execute a block of code in an if statement you need to do
if(something){
response;
}
So it should be this:
private void playerHealth() {
if (player.health <= 0) {
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
}

Related

I'm trying to exit while loop (while also using a for loop) in java

I am working on a project in which I must calculate mortgage. It's supposed to have a loan selection menu in which 1) uses default values to calculate the mortgage. 2) will allow the user to enter in custom values. 3) allows the user to exit the program and have the calculated values displayed. I have a for loop to allow the program to run up to 10 times (it can be less though). I'm currently using a do-while loop to exit the program when 3 is the selection. However it's not exiting. I"m not sure what is wrong and am hoping for an explanation and some tweaks I could implement to ensure it does what it's supposed to.
do
{
int selection = 0;
for(int i=0; i<loanArray.length; i++)
{
System.out.println("Please choose from the following choices below: ");
System.out.println("\t1) Promotional Loan (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("Please enter your selection(1-3): ");
selection = s.nextInt();
if(selection ==1)
{
loanArray[i] = new Mortgage();
System.out.println(loanArray[i].toString());
}
else if (selection ==2)
{
loanArray[i].storeLoanAmount();
loanArray[i].storeInterestRate();
loanArray[i].storeTerm();
System.out.println(loanArray[i].toString());
}
else if(selection == 3)
{
programSelection = false;
programRunning = false;
}
}//end of for array loop
}while (programSelection == true); //end of selection while loop
System.out.println("Exit Test"); //print statement to test if selection screen exited
I haven't actually tested this, but I think the problem is exiting the for loop. The quickest way to test that is just to use a break statement with a label.
outerLoop:
do
// ...
else if(selection == 3)
{
break outerLoop;
}
}//end of for array loop
}while (programSelection == true); //end of selection while loop
Break statements with labels are discussed in the Java tutorial.
Add a break; after the programRunning = false;
you have got the correct the logic the reason is the for loop.
while (programSelection == true)
will only be executed after the for loop. Need to be cautious as well because if the loanArray length is 1 you might think the code works well,actually it doesnt.

Delete this token (else)

ok so i was playing round with some code and adding new line as i'm learning java. i got this error "syntax error token "else" delete this token".
As im new to this could some one explain this error and what i should do, so i do not make the same mistake again.
class Years {
public static void main (String[] args){
int age = 30;
if (age <30){
System.out.println("you are young");
}else{
System.out.println("you are old ");
if (age > 1240);
}else{
System.out.println("dam son your still a bady");
if (age < 25);
{
System.out.println("You are Really old son!!");
}else{
System.out.println("you better Hide your age son!!");
}
}
}
}
You have an unconditional else block - you can't follow that with another else. So this is fine:
if (condition) {
...
} else if (otherCondition) {
...
} else {
...
}
But this isn't - because it doesn't make sense:
if (condition) {
...
} else {
...
} else {
...
}
An else block without a condition is meant to run unconditionally if the condition above it was not satisfied - in your case, the middle block is always run, so it's meaningless to have another.
Also note that you have:
if (age > 1240);
... which I suspect you didn't really intend. Likewise:
if (age < 25);
Both of these are if statements with empty bodies.
It's really unclear what you expect to achieve in each case - but I'd strongly advise you to have something like:
// List all the age boundaries in increasing order...
if (age < 25) {
...
} else if (age < 30) {
...
} else if (age < 1240) {
...
} else {
...
}
Now exactly one of those bodies will be executed.
You have a condition which doesn't make sense:
if (something) {
} else {
} else {
}
How do you expect the system to know which "else" block to use? else logically means "otherwise, do this" and effectively captures all remaining conditions. You can't do that more than once.
It looks like you've got an if statement that's in the wrong place. Try this instead:
if (age <30){
System.out.println("you are young");
}else if (age > 1240){
System.out.println("you are old ");
}else{
System.out.println("dam son your still a bady");
if (age < 25);
{
System.out.println("You are Really old son!!");
}else{
System.out.println("you better Hide your age son!!");
}
}
}
First understand how if statements work in any programming language. For example this is a good resource for you to understand if statements in java. I'm not 100% sure about what are you trying achieve by this code. But I can give you one hint. When branching, use not only else but also else if().

while loop not ending when required

So some background information, I'm new to programming and am still learning, so I apologize for my trivial error making. I am making my own text based game just to further practice etc.
Here is the link to everything on dropbox for more context:
https://www.dropbox.com/sh/uxy7vafzt3fwikf/B-FQ3VXfsR
I am currently trying to implement the combat system for my game, and I am running into the issue of the combat sequence not ending when required. The 'combat sequence' is a while loop as follows:
public void startCombat()
{
inCombat = true;
while(inCombat != false)// && herohealth > 0 && monsterhealth > 0)
{
checkAlive();
heroHitMonster();
checkAlive();
monsterHitHero();
}
attackinghero.setHeroHealth(herohealth);
attackedmonster.setMonsterHealth(monsterhealth);
}
where the checkAlive() method is as follows:
public void checkAlive()
{
if(herohealth <= 0)
{
System.out.println("You have died.");
attackinghero.clearInventory();
inCombat = false;
}
else if(monsterhealth <= 0)
{
System.out.println("You have killed the "+attackedmonster.getmonsterName()+"!");
inCombat = false;
combatlocation.removeMonster(attackedmonster.getmonsterName());
}
else
{
//
}
}
I am trying to get it to end the combat sequence when either the 'hero' or 'monster' health become <= 0,
however it is currently finishing the while loop and therefore producing the result of the hero being hit even if he killed the monster in his first hit.
This is what is currently being 'printed to screen'
rat loses 5 health!
You have killed the rat!
Hero loses 1 health!
Any help is much appreciated, thanks in advance.
checkAlive shouldn't be void it should be Boolean and should return inCombat, and in your function startCombat you should do inCombat=checkAlive();
The while loop will only evaluate after both actions. You need a way to break the loop after the hero hits the monster. I would personally change the checkAlive method to return a boolean, and put the hit methods in if statements in the while loop:
if(checkAlive())
{
heroHitMonster();
}
if(checkAlive())
{
monsterHitHero();
}
You should end the loop at the end of the checkAlive instead of changing the boolean value.
If you killed the monster at first hit, you still execute the monsterHitHero() even, if the monster is killed. The function to hit should be conditioned to the life of heroes/monster.

Method calling and display issue

I am new to java and the coding is probably sloppy so please don't be harsh! Anyways, I am making a method that will set increase in turn by 1 each time I hit the end turn button.
public int turns (int turn){
int turns = 0;
if (turn == 0){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn++;
}
if (turn == 1){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn++;
}
if (turn == 2){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn++;
}
if (turn == 3){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn = 0;
}
return(turns);
}
private void btnEndTurnActionPerformed(java.awt.event.ActionEvent evt) {
int turns = 0;
lblturn.setText("" +turns(turns));
When I run the program, the label constantly repeats 0 whenever I hit the button. I was thinking that int turns; would work, but the variable isn't initialized. I do not know if there is an error in my method, or if the initialization in the button is overriding the method.
As I said, i'm new to java so this might be the entirely wrong approach, and if it is, please give me some recommendations on how to improve this kind of structure. Thanks!
int turns = 0; on the second line is a local variable so the value get reset every time the method is called. You need to make it as a field of a class so that it can be shared between method. And also change turn++ to turns++.
You should be having turns++ not turn++

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