Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn an array of Strings into an Array of Ints?

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;
    } 
}
like image 363
Avi Caspe Avatar asked Dec 08 '22 03:12

Avi Caspe


2 Answers

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();
}
like image 135
Eran Avatar answered Dec 11 '22 08:12

Eran


Off-by-one error here:

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

It should be:

for (int i = 0; i < arrayString.length; i++ ) { 
like image 41
Adam Stelmaszczyk Avatar answered Dec 11 '22 09:12

Adam Stelmaszczyk