1

これまでの私のコードは次のとおりです(まあ、whileループ):

public class Lab10d
{
public static void main(String args[])
{
    Scanner keyboard = new Scanner(System.in);
    char response = 0;


    //add in a do while loop after you get the basics up and running

        String player = "";

        out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: ");

        //read in the player value
        player = keyboard.next();

        RockPaperScissors game = new RockPaperScissors(player);
        game.setPlayers(player);
        out.println(game);
    while(response == ('y'))
    {
        out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: ");
        player = keyboard.next();
        game.setPlayers(player);
        //game.determineWinner();
        out.println(game);
        out.println();

        //



    }
    out.println("would you like to play again? (y/n):: ");
        String resp =  keyboard.next();
        response = resp.charAt(0);
}
}

nが入力されるまで、コードを追加で実行することになっています

ayと入力すると、コードが再実行されるはずですが、実行されません

4

1 に答える 1

4

もう一度whileプレイするかどうかを尋ねる前に、ループは終了します。

ループを次のように変更します。

while(response == ('y'))
    {
        out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: ");
        player = keyboard.next();
        game.setPlayers(player);
        //game.determineWinner();
        out.println(game);
        out.println();
        out.println("would you like to play again? (y/n):: ");
        String resp =  keyboard.next();
        response = resp.charAt(0);
    }

別の問題があります:responseループが開始される前に「y」に設定されていません。ループ内では何もしません。do { ... } while (response == 'y')代わりにループを使用してください。

    do
    {
        out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: ");
        player = keyboard.next();
        game.setPlayers(player);
        //game.determineWinner();
        out.println(game);
        out.println();
        out.println("would you like to play again? (y/n):: ");
        String resp =  keyboard.next();
        response = resp.charAt(0);
    } while (response == 'y');

do-whileは、コードを1回実行してから、条件を確認し、そうである場合は実行を継続しますtrue。whileループは条件をチェックするだけで、その間実行を続けtrueます。

編集:私はあなたのためにいくつかのコードをまとめました:

import java.util.Scanner;

public class Troubleshoot {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        char response = ' ';
        do {
            System.out.println("Stuff");
            System.out.print("Again? (y/n): ");
            response = s.next().charAt(0);
        } while (response == 'y');
    }

}

出力:

Stuff
Again? (y/n): y
Stuff
Again? (y/n): y
Stuff
Again? (y/n): n
于 2012-11-08T01:53:25.747 に答える