java - 如何要求用户重新输入他们的选择?
问题描述
如果用户输入低于 10 或高于 999 的数字,我知道如何显示错误消息,但我如何编写代码以确保在用户输入低于 10 或高于 999 的数字后程序不会结束并给他们一个第二次机会一遍又一遍地输入他们的有效输入,直到他们给出正确的输入。
import java.util.Scanner;
public class Ex1{
public static void main(String args[]){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter an integer between 10 and 999: ");
int number = input.nextInt();
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
}
解决方案
您将需要使用一个循环,基本上,它会围绕您的代码循环,直到满足某个条件。
一个简单的方法是使用do/while
循环。对于下面的示例,我将使用所谓的“无限循环”。也就是说,除非有什么东西破坏了它,否则它将永远循环下去。
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start a loop that will continue until the user enters a number between 1 and 10
while (true) {
System.out.println("Please enter a number between 1 - 10:");
num = scanner.nextInt();
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
} else {
// Exit the while loop, since we have a valid number
break;
}
}
System.out.println("Number entered is " + num);
}
}
MadProgrammer 建议的另一种方法是使用do/while
循环。对于这个例子,我还添加了一些验证来确保用户输入一个有效的整数,从而避免一些异常:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start the loop
do {
System.out.println("Please enter a number between 1 - 10:");
try {
// Attempt to capture the integer entered by the user. If the entry was not numeric, show
// an appropriate error message.
num = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Please enter only numeric characters!");
num = -1;
// Skip the rest of the loop and return to the beginning
continue;
}
// We have a valid integer input; let's make sure it's within the range we wanted.
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
}
// Keep repeating this code until the user enters a number between 1 and 10
} while (num < 1 || num > 10);
System.out.println("Number entered is " + num);
}
}
推荐阅读
- c# - 工具提示的样式只能部分起作用
- flutter - Flutter Switch - onChanged 不随动态值变化
- c# - 如何将新列添加到 CSV 并使用 CSVHelper 将其写回另一个 CSV
- python - 检查列表元素是否在字符串索引列表中
- python - 错误:没有为张量流找到匹配的分布
- api - SHOPIFY 中的 VUE JS:添加到购物车产品后购物车属性未更新
- pytorch - 确保 BERT 模型不加载预训练的权重?
- powershell - 在powershell中过滤和删除超过x天的文件和文件夹(以及文件夹内的文件)
- node.js - node.js Socket.io cors 从 null
- java - 我正在尝试编写一个代码来检查 2 到 1000 之间的数字是否是素数