gpt4 book ai didi

java - 我如何要求用户重新输入他们的选择?

转载 作者:行者123 更新时间:2023-11-30 05:43:16 25 4
gpt4 key购买 nike

如果用户输入低于 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);

}
}

关于java - 我如何要求用户重新输入他们的选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55292685/

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