gpt4 book ai didi

java - 尽管满足条件,while 循环仍不循环

转载 作者:行者123 更新时间:2023-11-29 03:40:44 25 4
gpt4 key购买 nike

到目前为止,这是我的代码(好吧,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 时,它应该重新运行代码但没有

最佳答案

您的 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

关于java - 尽管满足条件,while 循环仍不循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13281296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com