Brian Shook
Brian Shook

Reputation: 13

Inputing strings into an array

I'm a beginning programmer with the assignment to create a program that prompts the user to enter the number of elements that will then be stored into a String array. The second part of the assignment is to then list the array in ascending order. But I'm kind of stuck of the first part. If the user enters that there will be 3 elements after the 3rd string is entered I get an out of bounds exception. Below is the code.

import java.util.*;
public class arrays
{
    public static void main(String[]arg)
    {
         Scanner input = new Scanner(System.in);
         //Read user  input.                 
         System.out.print("How many Elements?  ");                
         int num = input.nextInt();
         String array[]= new String[num];                 

         for (int i = 1 ; i <= num; i++ )               
         {                      
             System.out.print("Enter element "+ i +":  ");
             array[i] = input.next();
         }
         System.out.println(array);
     }
}

Upvotes: 0

Views: 68

Answers (5)

Marvin
Marvin

Reputation: 14255

The array index starts at 0 so your loop should look like this:

for (int i = 0 ; i < num; i++ )               
{                      
    System.out.print("Enter element "+ (i+1) +":  ");
    array[i] = input.next();
}

Note that I also added +1 in the System.out.print to show "user friendly" output (e.g. "Enter element 1:" instead of "Enter element 0:" for the first element).

Another option would be to subtract 1 while accessing the array, which would allow you to keep the existing System.out.print line:

for (int i = 1 ; i <= num; i++ )               
{                      
    System.out.print("Enter element "+ i +":  ");
    array[i - 1] = input.next();
}

Although I feel that this is slightly less common practice.

Upvotes: 2

OPK
OPK

Reputation: 4180

you get the error because array index starts with 0. You should change your loop into this:

for (int i = 0 ; i < num; i++ )

Upvotes: 0

Matthias Reiher
Matthias Reiher

Reputation: 1

Start with i = 0 and go up to i < num, because in the example with three your array starts at 0 and goes up to 2, so it's no wonder that there's an out of bounds exception. That should fix the error.

Upvotes: 0

harsh
harsh

Reputation: 7692

change to array[i-1] = input.next();

Upvotes: -1

Florian Schaetz
Florian Schaetz

Reputation: 10652

Arrays in Java are numbered starting with zero, which means, your array of length 3 has this valid indices:

array[0]
array[1]
array[2]

I guess that's enough to send you on the right track ;-)

Upvotes: 0

Related Questions