Converting String Array to an Integer Array
Asked Answered
A

8

44

so basically user enters a sequence from an scanner input. 12, 3, 4, etc.
It can be of any length long and it has to be integers.
I want to convert the string input to an integer array.
so int[0] would be 12, int[1] would be 3, etc.

Any tips and ideas? I was thinking of implementing if charat(i) == ',' get the previous number(s) and parse them together and apply it to the current available slot in the array. But I'm not quite sure how to code that.

Adkison answered 16/9, 2013 at 23:7 Comment(4)
What's your code for the scanner input?Curium
This is a duplicate question #6881958Aciculate
Here is a function that should help you: https://mcmap.net/q/366050/-converting-a-string-array-into-an-int-array-in-javaMaidstone
Does this answer your question? Converting a String Array to an Int arrayEager
F
74

You could read the entire input line from scanner, then split the line by , then you have a String[], parse each number into int[] with index one to one matching...(assuming valid input and no NumberFormatExceptions) like

String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
   // Note that this is assuming valid input
   // If you want to check then add a try/catch 
   // and another index for the numbers if to continue adding the others (see below)
   numbers[i] = Integer.parseInt(numberStrs[i]);
}

As YoYo's answer suggests, the above can be achieved more concisely in Java 8:

int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();  

To handle invalid input

You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.

If you don't need to know about invalid input but just want to continue parsing the array you could do the following:

int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
    try
    {
        numbers[index] = Integer.parseInt(numberStrs[i]);
        index++;
    }
    catch (NumberFormatException nfe)
    {
        //Do nothing or you could print error if you want
    }
}
// Now there will be a number of 'invalid' elements 
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);

The reason we should trim the resulting array is that the invalid elements at the end of the int[] will be represented by a 0, these need to be removed in order to differentiate between a valid input value of 0.

Results in

Input: "2,5,6,bad,10"
Output: [2,3,6,10]

If you need to know about invalid input later you could do the following:

Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)        
{
    try 
    {
        numbers[i] = Integer.parseInt(numberStrs[i]);
    }
    catch (NumberFormatException nfe)   
    {
        numbers[i] = null;
    }
}

In this case bad input (not a valid integer) the element will be null.

Results in

Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]


You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.

Fanchan answered 16/9, 2013 at 23:10 Comment(2)
Java Devil, what do you mean by this "// and another index for the numbers if to continue adding the others"? What if I want to add the others to the array?Schnorrer
@Schnorrer It was merely a suggestion to deal with invalid input. Consider the input 4,6,z,10. Here the z would cause a NumberFormatException so if continued using i as the index there would be a null at the third position in the Integer Array. It just depends on how you want to deal with that scenario. The extra index I was talking about was to just ignore the z so in the final Integer array, the third number would be 10.Fanchan
P
43

Line by line

int [] v = Stream.of(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

With the Arrays.stream() alternative as

int [] v = Arrays.stream(line.split(",\\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

However much better for parsing bigger chunks of text is

int [] v = Pattern.compile(",\\s+").splitAsStream(line)
  .mapToInt(Integer::parseInt)
  .toArray();  

As this does not require the string array to be in memory, and we do an incremental parse to produce the integers. Moreover, as the input to splitAsStream is a CharSequece, and not just String, we can now also used buffered character sources to avoid even having the full input source in memory.

See also How do I create a Stream of regex matches? for some more interesting reading on incremental parsing.

Placard answered 7/5, 2016 at 19:54 Comment(0)
B
6

Stream.of().mapToInt().toArray() seems to be the best options.

int[] arr = Stream.of(new String[]{"1", "2", "3"})
                  .mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));
Bechuana answered 22/7, 2019 at 18:42 Comment(0)
A
4

For Java 8 and higher:

    String[] test = {"1", "2", "3", "4", "5"};
    int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();
Ayeshaayin answered 4/2, 2021 at 16:7 Comment(1)
Does not answer 'I want to convert the string input to an integer array' and this part answer is sufficiently covered in other answers, although you do offer the alternative Arrays.stream() instead of Stream.of().Placard
M
2

Converting String array into stream and mapping to int is the best option available in java 8.

    String[] stringArray = new String[] { "0", "1", "2" };
    int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
    System.out.println(Arrays.toString(intArray));
Moffat answered 18/11, 2020 at 10:19 Comment(1)
Again, this just covers alternative forms of converting String [] --> int [], not String --> int [] (missing the delimiter parsing step).Placard
E
0
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class MultiArg {

    Scanner sc;
    int n;
    String as;
    List<Integer> numList = new ArrayList<Integer>();

    public void fun() {
        sc = new Scanner(System.in);
        System.out.println("enter value");
        while (sc.hasNextInt())
            as = sc.nextLine();
    }

    public void diplay() {
        System.out.println("x");
        Integer[] num = numList.toArray(new Integer[numList.size()]);
        System.out.println("show value " + as);
        for (Integer m : num) {
            System.out.println("\t" + m);
        }
    }
}

but to terminate the while loop you have to put any charecter at the end of input.

ex. input:

12 34 56 78 45 67 .

output:

12 34 56 78 45 67
Edmea answered 21/5, 2015 at 5:4 Comment(0)
M
0

    string[] test = new string[2] {"12","13"};

    int[] resault = Array.ConvertAll(test, s => int.Parse(s));

resault is [12,13];

Matriarchy answered 17/1 at 13:47 Comment(0)
U
-3

Java has a method for this, "convertStringArrayToIntArray".

String numbers = sc.nextLine();
int[] intArray = convertStringArrayToIntArray(numbers.split(", "));
Unrestraint answered 30/8, 2020 at 15:9 Comment(2)
Which package and class is it?Fala
@EugeneMamaev it is in org.alfonz.utility github.com/petrnohejl/Alfonz/blob/…Pingpingpong

© 2022 - 2024 — McMap. All rights reserved.