0

プレイヤーがボスを攻撃し、プレイヤーがボスを倒そうとするこのシンプルなアプリを作成しました。私が問題を抱えているのは、ボスが倒された後に小さなJavaアプリを印刷することです。私の上司の健康状態は 5 で、1 から 6 の範囲のランダム ダイス ジェネレーターがあります。プレイヤーが最初の攻撃で「5」または「6」をロールしたら、プログラムを終了させたいと思います。もう 1 つの問題は、プレイヤーが 5 または 6 のダメージを与えていないのに、私のプログラムが I've goted the Boss を出力することです。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!
4

1 に答える 1

0

スキャナーを閉じませんでした。

ボスを倒さないためのテストは、for ループの外にある必要があります。

どのヒットが残っているかを確認するには、別の変数 (追加) が必要でした。

最初のロールで勝った場合は、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!");
                break;
            } else {
                int more = 5 - total;
                System.out.println("You need " + more
                        + " more hits to defeat the boss!");

            }

        }
        if (total < 5) {
            System.out.println("Sorry, you did not defeat the boss");
        }
        attack.close();
    }
}
于 2013-02-16T01:15:32.100 に答える