首页 > 解决方案 > 如何要求用户重新输入他们的选择?

问题描述

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

标签: java

解决方案


您将需要使用一个循环,基本上,它会围绕您的代码循环,直到满足某个条件。

一个简单的方法是使用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);

    }
}

推荐阅读