首页 > 解决方案 > 如何确保用户输入在给定的有效范围内?

问题描述

我目前正在编写一个代码来生成一个由 1-20 的星号组成的空心正方形。这是我到目前为止所拥有的,但是如果用户输入一个大于 20 的数字,我无法弄清楚如何将代码循环回自身。例如,如果用户输入 21,代码仍然会创建星号方块并在下方弹出“Invalid Size. Enter Size from 1-20:”文本重新提示用户,但新的数字不会产生任何结果。我需要它不创建正方形(如果 > 20 或 <= 0),而是直接“跳转”到 Invalid Size 文本,然后如果用户的输入在 1-20 范围内,则创建一个正方形。如果他们的输入再次> 20,我需要它再次提示无效。任何建议或帮助将不胜感激!非常感谢您花时间阅读本文。:)

import java.util.Scanner; // program uses class Scanner

    public class HollowSquare {

    public static void main(String[] args) {

        // variable declaration
        int x;
        int s;
        int p;
        int r = 0;
        int y = 1;
        int z = 1;
        int f = 1;

        Scanner input = new Scanner(System.in);

        System.out.printf("Enter the Size of the Asterisk Square from 1-20: "); // prompt user
        x = input.nextInt();  
        if (x > 0 || x <= 20);

        // read and store data from user
        s = x + 2;
        p = x - 2;

        // print output
        while (y <= x) 
        {
            System.out.printf(" * ");
            y++;
        }
        while (r < p) 
        {
            System.out.print("\n * ");
            while (z <= p) 
            {
                System.out.print("   ");
                z++;
            }
            System.out.print(" * ");
            r++;
            z=1;
        }
        System.out.print("\n");
        if (x > 1)
        {
            while (f <= x) 
            {
                System.out.printf(" * ");
                f++;
            }
            System.out.printf("\n");
        }
        else
                System.out.printf("\n");

     // conditions
        if (x <= 0 || x > 20)
            System.out.println("Invalid Size. Enter Size from 1-20: ");
            x = input.nextInt();
    } // end main method
} // end class HollowSquare

标签: javaloopsvalidation

解决方案


循环直到你得到满意的输入:

int x=0;
/*   ... */
while (x < 1 || x > 20)
{
    System.out.printf("Enter the Size of the Asterisk Square from 1-20: "); // prompt user
    x = input.nextInt();  
}

推荐阅读