java - 当用户没有在数组中输入任何数字或在数组中输入太多数字时打印出错误消息
问题描述
你好 java 专业人士和专家,我遇到的第一个问题是在我的程序中实现一个代码,当用户没有输入任何数字并且数组为空时,它会告诉用户“没有输入数字”。
我遇到的第二个问题是如果用户输入的数字过多,则执行代码,发出错误消息,指出已超出数组的大小;然后打印出下一行输入的数字。
到目前为止,这是我的代码:
import java.util.Scanner;
public class FunWithArrays
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 10; // Size of the array
// Create an array.
int[] numbers = new int[ARRAY_SIZE];
// Pass the array to the getValues method.
getValues(numbers);
System.out.println("Here are the " + "numbers that you entered:");
// Pass the array to the showArray method.
showArray(numbers);
}
public static void getValues(int[] array)
{
// Create a Scanner objects for keyboard input.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a series of " + array.length + " numbers.");
// Read the values into the array
for (int index = 0; index < array.length; index++)
{
System.out.print("Enter the number " + (index + 1) + ": ");
array[index] = keyboard.nextInt();
}
}
public static void showArray(int[] array)
{
// Display the array elements.
for (int index = 0; index < array.length; index++)
System.out.print(array[index] + " ");
}
}
我想知道您的专业人士或专家是否对如何在不更改程序中的任何代码的情况下解决此问题有任何建议?我的教授指示我为这个问题做一个 do-while 循环,但不知道如何为它创建代码......有什么建议吗?
解决方案
推荐阅读
- unit-testing - DataTable/DataSet 到 IFormFile(Excel) 到单元测试
- javascript - 在 Node.js 的循环中移动到下一个迭代之前等待 Promise
- java - 检查运行 JAR Linux 服务的版本
- laravel - Laravel 版本升级影响你的控制器?
- c# - ASP.NET Core,实体框架 - Word 文档
- c++ - 重用字符串流而不重新分配
- openapi - OpenAPI 规范 lint 工具,“规范架构无效。”
- makefile - 如果使用特定的内核构建 Makefile
- android - 找不到方法 compile() google gms
- vba - 当 VBA 中的组合框更改时,在多个文本框中添加月份名称