简体   繁体   English

为什么我的数组不打印我的输入?

[英]Why doesn't my array print out my input?

I am trying to make an app that asks the user to input the number of items in an array, and then ask them to fill up that array with integers. 我正在尝试制作一个应用程序,要求用户输入数组中的项数,然后要求他们用整数填充该数组。 And after, to print it out. 然后,将其打印出来。

When I run it it asks me to input, but then gives me: 当我运行它时,它会要求我输入,但随后会给我:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at main.main(main.java:13) 线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:main.main处为10(main.java:13)

import java.util.Scanner;

public class main {
public static void main(String [] args){
    Scanner scan = new Scanner(System.in);
    System.out.println("Input number of units in array: ");
    int i1 = scan.nextInt();
    int[] arrayOne= new int[i1];

    for(int i=0 ; i<=i1 ; i++){

        System.out.println("Enter " + i + " unit in array.");
        arrayOne[i] = scan.nextInt();

    }


    System.out.println(arrayOne);


}

}

Can you guys help me spot where my mistake is? 你们可以帮我找出我的错误所在吗? I tried a few different things, but nothing seems to work. 我尝试了几种不同的方法,但似乎没有任何效果。

Thanks! 谢谢!

Arrays are zero based. 数组从零开始。 Here you're exceeding the upper bound. 在这里,您超出了上限。 Replace: 更换:

for (int i = 0; i <= i1; i++) {

with

for (int i = 0; i < i1; i++) {

Also use Arrays#toString to display the array contents, otherwise the Object#toString representation of the array will be displayed: 还要使用Arrays#toString显示数组内容,否则将显示数组的Object#toString表示形式:

System.out.println(Arrays.toString(arrayOne));

Your code seems like you need to make a new scan each time in your loop. 您的代码似乎需要在循环中的每一次进行新的扫描。

You are also doing one iteration too many (compared to the size of your array). 您也进行了太多次迭代(与数组大小相比)。

Probably this code will work better: 此代码可能会更好地工作:

import java.util.Scanner;

public class Main 
{
    public static void main(String [] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Input number of units in array: ");
        int i1 = scan.nextInt();
        int[] arrayOne= new int[i1];
        for(int i=0 ; i<i1 ; i++)
        {
            System.out.println("Enter " + i + " unit in array.");
            Scanner other_scan = new Scanner(System.in);
            arrayOne[i] = other_scan.nextInt();
        }
        for(int i=0 ; i<i1 ; i++)
        {
            System.out.println("arrayOne["+i+"]: "+arrayOne[i]);
        }       
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM