首页 > 解决方案 > 如果在 Java 中不满足“X”值,则在循环中重新打印行

问题描述

如果不满足值,我正在尝试让我的代码重新打印一行。

我试过使用while,但如果'X'不大于或等于1,它不会回到问题。

我目前正在尝试:

    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;
                }
            }
    }

但是当 hp 仍然大于 1 时,我无法重新说明问题。

标签: javaeclipsewhile-looptext-based

解决方案


这应该可以阅读评论

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");
    }
}

推荐阅读