首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尽管满足条件,while循环仍未循环

尽管满足条件,while循环仍未循环
EN

Stack Overflow用户
提问于 2012-11-08 09:50:09
回答 1查看 3.3K关注 0票数 1

下面是我到目前为止的代码(好吧,while循环):

代码语言:javascript
复制
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时,它应该重新运行代码,但没有

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-08 09:53:26

在你询问他们是否还想玩之前,你的while循环结束了。

将循环更改为:

代码语言:javascript
复制
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')循环。

代码语言:javascript
复制
    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时继续执行。

编辑:我为你整理了一些代码:

代码语言:javascript
复制
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');
    }

}

输出:

代码语言:javascript
复制
Stuff
Again? (y/n): y
Stuff
Again? (y/n): y
Stuff
Again? (y/n): n
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13281296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档