我有一段时间没有编程,我正在努力回到事物的摇摆中,这就是我已经走了多远。我的问题是,如何循环第二个问题,以便如果响应是除了是或否之外它再次询问问题。我试过在if语句周围放一个循环,但每当我尝试从用户那里得到另一个响应时,它告诉我我不能使用变量 response 来这样做。我觉得这是一个很容易解决的问题,因为我理解循环,但是我很难绕过这个具体问题,谢谢你。
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to my simulation, please enter your name");
String name = input.nextLine();
System.out.println("Welcome " + name + " would you like to play a game?");
String response = input.nextLine();
boolean yes = new String("yes").equals(response.toLowerCase());
boolean no = new String("no").equals(response.toLowerCase());
if (yes){
System.out.println("Which game woudl you like to play?");
}else if (no){
System.out.println("Fine then, have a good day!");
}
else{
System.out.println("please enter either yes or no");
}
}
}
答案 0 :(得分:5)
有很多方法可以做到这一点。这是我想到的第一个:
while (true) {
response = input.nextLine().toLowerCase();
if (response.equals("yes") {
System.out.println("Which game woudl you like to play?");
break;
} else if (response.equals("no") {
System.out.println("Fine then, have a good day!");
break;
} else {
System.out.println("please enter either yes or no");
}
}
答案 1 :(得分:0)
首先,为了让自己更轻松,您不需要使用boolean
个变量。您只需使用.equals()
方法来测试响应是否等于是或否。在这种情况下,如果使用else语句会更容易使用:
if (response.equals("Yes"))
{
System.out.println("Which game woudl you like to play?");
}
else if (response.equals("No"))
{
System.out.println("Fine then, have a good day!");
}
else if (!response.equals("Yes") && !response.equals("No"))
{
while (!response.equals("Yes") && !response.equals("No"))
{
System.out.println("please enter either yes or no");
response = input.nextLine();
}
}
希望这对你有所帮助。
答案 2 :(得分:-1)
怎么样
do{
String response = input.nextLine();
boolean yes = new String("yes").equals(response.toLowerCase());
boolean no = new String("no").equals(response.toLowerCase());
if (yes){
System.out.println("Which game woudl you like to play?");
}else if (no){
System.out.println("Fine then, have a good day!");
}
else{
System.out.println("please enter either yes or no");
}
}while(!response.equals("yes") && !response.equals("no"));