错误消息表示已超出数组



我想知道你们能否给我一些关于如何修复代码的建议。我试图发出一条错误消息,当您输入的数字太多时,数组的大小已被超出。我知道我写了两篇关于这件事的帖子,很多人告诉我要具体,自己做,我决定自己做这个项目,而不是寻求帮助。所以我写了代码,结果很好,但当它说"输入数字11"时,我该怎么做呢?然后我输入一个数字,它说它已经超过了,并在下一行打印出10个数组。

输入:

import java.util.Scanner;
public class FunWithArrays
{
public static void main(String[] args)
{
final int ARRAY_SIZE = 11; // 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++)
{
// To tell users if they exceeded over the amount
if (index > 9)
{
System.out.print("You exceeded the amount " + " ");
}
else
{
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] + " ");
}
}

输出:

Enter a series of 11 numbers.
Enter the number 1: 3321
Enter the number 2: 3214
Enter the number 3: 213
Enter the number 4: 21
Enter the number 5: 321
Enter the number 6: 321
Enter the number 7: 3
Enter the number 8: 213
Enter the number 9: 232
Enter the number 10: 321
You exceeded the amount  Here are the numbers that you entered:
3321 3214 213 21 321 321 3 213 232 321 0

好吧,这是您需要的代码,记住第11个元素根本没有放入数组中。

public static void main(String[] args) {
final int ARRAY_SIZE = 11; // 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++) {
// To tell users if they exceeded over the amount
if (index >= 10) {
System.out.print("Enter the number " + (index + 1) + ": ");
array[index] = keyboard.nextInt();
System.out.println("nYou exceeded the amount " + " ");
} else {
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-1; index++) {
System.out.print(array[index] + " ");
}
}
}

我不知道,你为什么要这样。

最新更新