我制作了一个简单的应用程序,其中玩家攻击老板,玩家必须尝试击败老板。我遇到的麻烦是在老板被击败后打印我的小型 Java 应用程序。我老板的生命值为 5,我有一个随机骰子生成器,范围为 1 - 6。当玩家在第一次攻击中掷出“5”或“6”时,我希望程序结束。另一件事是我的程序打印出我已经击败了老板,即使玩家没有造成 5 或 6 点伤害。我认为这可能是因为 for 循环,但我不确定。
这是代码:
import java.util.Scanner;
import java.util.Random;
public class Hey{
public static void main (String args[]){
Scanner attack = new Scanner(System.in);
Random dice = new Random();
String hits;
int hitss,total = 0;
System.out.println("Time to attack the boss!");
System.out.println("Press letter 'A' to attack!");
hits = attack.next();
hitss = 1+dice.nextInt(6);
for(int i=0;i<2;i++){
if(hits.equals ("a")){
System.out.println("You have hit a " + hitss);
total += hitss;
}
if(total >= 5){
System.out.println("Well done, You have defeated the boss!");
}
else if(total < 5){
total = 5 - total;
System.out.println("You need " + total + " more hits to defeat the boss!");
}
else
{
System.out.println("Sorry, you did not defeat the boss");
}
}
}
}
输出:
You have hit a 2
You need 3 more hits to defeat the boss!
You have hit a 2
Well done, You have defeated the boss!