java - 如何保证用户输入在给定的有效范围内?

标签 java loops validation

我目前正在编写一个代码来生成一个由 1-20 的星号组成的空心正方形。这是我到目前为止所得到的,但是如果用户输入一个> 20的数字,我无法弄清楚如何将代码循环回来。例如,如果用户输入21,代码仍然会创建星号方 block 并在下方弹出“Invalid Size. Enter Size from 1-20:”文本重新提示用户,但新的数字不会产生任何结果。我需要它不创建正方形(如果 > 20 或 <= 0),而是直接“跳转”到“无效大小”文本,然后如果用户的输入在 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

最佳答案

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

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();  
}

关于java - 如何保证用户输入在给定的有效范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51450179/

相关文章:

javascript - 如何使用 2 个表单集并保存它们(POST 方法问题)

asp.net - 如何验证文件上传的文件类型?

java - Statement.executeQuery() 在 MySQL 中执行 SELECT 命令时抛出 java.sql.SQLSyntaxErrorException

java - 从泛型类中获取枚举列表

java - 设计带有2个外键的spring data jpa注释类

Javascript 添加前导零适用于 while 循环,但不适用于 for 循环

java - 如何增加 'for-loop' 内的 char int 数组

arrays - 循环遍历数组并一次显示单个项目,并具有动态持续时间,例如react js中的setTimeout或SetInterval

c# - 如何强制 ValidationAttribute 将指定的对象成员标记为无效?

java - 遗留项目结构 : intellij recognizes gradle subproject as module but doesn't recognize its source code