java - In Java, how to restrict a user to enter only one type?
问题描述
In this case, I have asked the user to enter 1,2 or 3. If user enters string, it should ask the question again. when my code runs, every if statement is running, where as I want to run a specific if statement. It would be a huge favor if anyone could help me.
String question = "What is the color of banana? Write 1,2 or 3. Choose one of the following:";
String answerOne = "1. yellow";
String answerTwo = "2. red";
String answerThree = "3. blue";
while(true){
System.out.println(question + "\n" + answerOne + "\n" + answerTwo + "\n" + answerThree);
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
System.out.println("Please select a NUMBER between 1 and 3.");
}
if (input.hasNextDouble()) {
System.out.println("Please select a NUMBER between 1 and 3.");
}
if (input.hasNextInt()) {
int x = input.nextInt();
if (x == 1) {
System.out.println("Congratulations!! your answer is correct");
break;
}
if (x == 2 || x == 3) {
System.out.println("Sorry!! the correct answer is" + answerOne);
break;
}
if (x > 3) {
System.out.println("Please choose the correct answer!!");
}
}
}
}
解决方案
Ok, so first that's not how .hasSomething()
works, it used to check if there have more elements. So what you should do, is to read the input as a string and check that string:
String question = "What is the color of banana? Write 1,2 or 3. Choose one of the following:";
String answerOne = "1. yellow";
String answerTwo = "2. red";
String answerThree = "3. blue";
System.out.println(question + "\n" + answerOne + "\n" + answerTwo + "\n" + answerThree);
Scanner input = new Scanner(System.in);
String c = input.next();//read the input
while(!(c.charAt(0) >= '1' && c.charAt(0) <= '3') || c.length() != 1){ //check if it's a number between 1 and 3
System.out.println("Enter agin:");
c = input.next();
}
int x = Integer.parseInt(c);//change c to an integer
if (x == 1) {
System.out.println("Congratulations!! your answer is correct");
break;
}
if (x == 2 || x == 3) {
System.out.println("Sorry!! the correct answer is" + answerOne);
}
推荐阅读
- c++ - 创建 alignas(64) 整数的向量
- html - 如何使用 Angular js 创建带有选择和非选择复选框的下拉框,就像在下图中一样?
- python-3.x - 我的 GET 请求的状态码 400 - Mixpanel API
- imagemagick - ImageMagick - %d 可以与图像属性百分比转义一起使用吗?
- ios - AVFoundation 位置音频在 iOS 设备上不起作用
- javascript - 如何在多步表单上屏蔽输入
- javascript - HTML - document.write
- c# - 使用 c# 将 INO arduino 文件编译成 hex 文件
- c# - 仅在 DataGridSet 上显示的 SQL 条目
- sql-server - 如何使用滑动日期但特定时间进行动态 SQL Server 查询?