如何解决用户使用循环输入无效的信息
当用户输入无效时,我试图做一个while循环,这意味着它不是“是”或“否”,以便问题再次出现。如果您能在这里帮助我,我将不胜感激!谢谢(我删除了除问题以外的大多数代码,因为它太长了!!) 代码:
import java.util.Scanner;
import java.util.Random;
public class ShowWhatYouKnow {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
Random rd = new Random();
String ready;
int guess;
int[] dice = {1,2,3,4,5,6};
System.out.println("Welcome to dice game!");
System.out.println("");
System.out.println("Guess a number between 1-6 and win $50!!");
System.out.println("Are you ready??");
ready = key.nextLine();
// trying to do a do while here so if the user inputs the invalid option this would accur again and again
/*
System.out.println("invalid input !");
System.out.println("");
System.out.println("Guess a number between 1-6 and win $50!!");
System.out.println("Are you ready??");
ready = key.nextLine();
*/
if (ready.equalsIgnoreCase("yes")) {
System.out.println("Let The Game Begin!!");
System.out.println("-----------------------------------------");
}
} else if(ready.equalsIgnoreCase("no")){
System.out.println("You Exited The Program!! Bye!");
System.out.println("-----------------------------------------");
System.out.println("");
}
}
}
解决方法
使用无限循环并在输入正确时中断它
while (true) {
System.out.println("Guess a number between 1-6 and win $50!!");
System.out.println("Are you ready??");
ready = key.nextLine();
if (ready.equalsIgnoreCase("yes")) {
System.out.println("Let The Game Begin!!");
System.out.println("-----------------------------------------");
break;
} else if (ready.equalsIgnoreCase("no")) {
System.out.println("You Exited The Program!! Bye!");
System.out.println("-----------------------------------------");
System.out.println("");
break;
} else {
System.out.println("invalid input !");
}
}
,
您可以使用Do-while loop解决您的问题:如果用户输入的内容不是“是”或“否”,该问题将再次出现。您可以这样编写main方法:
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
Random rd = new Random();
String ready;
int guess;
int[] dice = {1,2,3,4,5,6};
System.out.println("Welcome to dice game!");
do {
System.out.println("");
System.out.println("Guess a number between 1-6 and win $50!!");
System.out.println("Are you ready??");
ready = key.nextLine();
} while (!ready.equalsIgnoreCase("yes") && !ready.equalsIgnoreCase("no"));
if (ready.equalsIgnoreCase("yes")) {
System.out.println("Let The Game Begin!!");
System.out.println("-----------------------------------------");
} else if (ready.equalsIgnoreCase("no")) {
System.out.println("You Exited The Program!! Bye!");
System.out.println("-----------------------------------------");
System.out.println("");
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。