简体   繁体   中英

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)

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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