4

I'm new to Java programming, but after looking around on this site, I'm fairly certain this should work.

 public static int[] ArrayStringToArrayInt(String[] arrayString) {
    int[] arrayInt = new int[arrayString.length]; //Array of Ints for output

    for (int i = 0; i <= arrayString.length; i++ ) {  //Run through the 
    arrayInt[i] = Integer.parseInt(arrayString[i]);   //array, Parsing each
    }                                                 //item into an int

    return arrayInt;
}

What I want this method to do is take an input array: ["1","2","3"] with each item being a string and return [1,2,3] where each item is an int.

I'm calling the method with this code

int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);

In this case, toBeSorted is both being declared here and initialized at the same time.

Whenever I try to run this I get the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at sorter.Sorter.ArrayStringToArrayInt(Sorter.java:31)
at sorter.Sorter.main(Sorter.java:22)   
Java Result: 1

Line 31 is the body of my For loop, the part that does the parsing, and line 22 is the place where the method is called.

The reason I need this is because I'm trying to take an input from the user, with the Scanner class and want them to be able to enter many numbers at the same time. I then use a delimiter pattern to turn the input into an array. While that seems fine, I could only figure out how to make the input be an array of strings, not ints, which is my problem.

So I guess what I'm asking is 1) why does my code not work? and 2) is there an easier way to take an input from the user and turn it into an array of ints than this?

For those who would like to see my entire code, here it is

The bit in the middle with the test variable and the adding of two numbers is just a way for me to test my code and see if it worked. It should show the result of adding the first two numbers in the list that you entered

package sorter;

import java.util.Scanner;
import java.util.Arrays;

public class Sorter {

public static void main(String[] args) {

    Scanner userInput = new Scanner( System.in );

    System.out.println("Enter a list to be sorted, seperate numbers by commas:");

    String input = userInput.nextLine(); //Gets aan input as a String
    String delims = "[,]+"; //Use Comma as Delimiter
    String[] inputStringArray = input.split(delims); //Parse String and creates
                                                //an array

    System.out.println(Arrays.toString(inputStringArray)); //Outputs a string of
                                                      //the given array

    int[] toBeSorted = ArrayStringToArrayInt(inputStringArray);
    int test = toBeSorted[0] + toBeSorted[1];
    System.out.println(test);
}

public static int[] ArrayStringToArrayInt(String[] arrayString) {
    int[] arrayInt = new int[arrayString.length]; //Array of Ints for output

    for (int i = 0; i <= arrayString.length; i++ ) {  //Run through the 
    arrayInt[i] = Integer.parseInt(arrayString[i]);   //array, Parsing each
    }                                                 //item into an int

    return arrayInt;
    } 
}
1
  • array.length will give you number of element not the index so you have to change the loop condition to i < arrayString.length Commented Apr 19, 2015 at 17:47

6 Answers 6

8

You got the range of the loop wrong :

for (int i = 0; i <= arrayString.length; i++ )

should be

for (int i = 0; i < arrayString.length; i++ )

The valid indices of the array are between 0 and arrayString.length - 1.

As a bonus, here's a nicer way to achieve the same with Java 8:

public static int[] ArrayStringToArrayInt(String[] arrayString) 
{
    return Stream.of(arrayString).mapToInt(Integer::parseInt).toArray();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. I momentarily forgot that array indexes start at 0 not 1. I feel stupid.
Wait a minute, how in the world does the fancy new java 8 thing work?
4

Off-by-one error here:

for (int i = 0; i <= arrayString.length; i++ ) { 
                   ^

It should be:

for (int i = 0; i < arrayString.length; i++ ) { 

2 Comments

@TedHopp It is called off-by-one error. Citing Wikipedia: It often occurs in computer programming when an iterative loop iterates one time too many or too few.
Fair enough. I was thinking of either a fencepost error or looping from 1 to n instead of 0 to n-1, but I see that modern usage is more general.
2

This is wrong

for (int i = 0; i <= arrayString.length; i++ )

should be

for (int i = 0; i < arrayString.length; i++ )

The indexes of the array are between the 0 and length -1

Comments

0

Variable i should go from 0 to N-1, N being the length of the array. Java arrays, like C ones are zero-based, which means that you should iterate them from 0 to N-1. So your for should look like this:

for (int i = 0; i < arrayString.length; i++)

Comments

0

You could use a stream:

Arrays.stream(arrayString).mapToInt(Integer::parseInt).toArray()

Comments

0

Simply change this statement

for (int i = 0; i <= arrayString.length; i++ )

To

for (int i = 0; i < arrayString.length; i++ )

It will work fine. ArrayIndexOutOfBoundsException means you're trying to access an index in the array that does not exist. For example,

int [] a= new int [5];

Then the indices available to me are

a [0], a [1], a [2], a [3], and a [4]

I cannot access

a [5]

And if i try i would get ArrayIndexOutOfBoundsException.

That means array indices start at 0 and go upto array length-1.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.