Search code examples
javaeclipsewhile-looptext-based

Re-printing line in a loop if 'X' value isn't met in Java


I am trying to make my code re-print a line if the value isn't met.

I have tried using while but it wont revert back to the question if 'X' isn't greater than or equal to 1.

I am currently trying:

    import java.util.Scanner;
public class rpg {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        double hp = 10;
        System.out.println("how much damage do you wish to do?");
        double attack = input.nextDouble();
        double damage = hp - attack;
        System.out.println(damage);
            System.out.println("health = " + Math.round(hp));
            while (hp <= 1) {
                System.out.println("Alive");
                break;
                }
            }
    }

but I can't get the question to re state when the hp is greater than 1 still.


Solution

  • This should work read the comments

    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        double hp = 10;
        while(hp > 1) { //Moved The loop
            System.out.println("how much damage do you wish to do?");
            double attack = input.nextDouble();
            //double damage = hp - attack;//not needed
            hp = hp - attack;//Added this line
            //System.out.println(damage);//not needed
            System.out.println("health = " + Math.round(hp));
            if(hp == 0)
                System.out.println("Dead");
            else
                System.out.println("Alive");
        }
    }