虽然条件得到满足,但循环不循环

时间:2012-11-08 01:50:09

标签: java loops while-loop

到目前为止,这是我的代码(好吧,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

当我输入y时,它应该重新运行代码但不是

1 个答案:

答案 0 :(得分: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将执行代码一次然后检查条件并继续执行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