java - 如何确保用户输入在给定的有效范围内?
问题描述
我目前正在编写一个代码来生成一个由 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
解决方案
循环直到你得到满意的输入:
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();
}
推荐阅读
- r - 使用 xlsx 包从 R 中导出的文件名中删除空格
- jquery - 如何使用 Jquery contextMenu X2 更新 contextMenu
- javascript - 用 Jest 模拟 Typescript 中导入函数的返回值
- javascript - onDoubleClick() 不适用于手机反应 js 应用程序
- php - 未定义的偏移量:php 中的 1
- asp.net-core - 生成 CrypoAPI (CAPI) 私钥
- asp.net - CLR 类型到 EDM 类型的映射是不明确的,因为有多个 CLR 类型;没有找到解决方案
- python - 如何使用 pytest 在循环中使用断言
- html - 悬停时显示全尺寸图像
- powerbi - 在 Power BI 中使用 USERNAME() 测量 if 条件