42

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.

Noctis
  • 11,507
  • 3
  • 43
  • 82
Mario
  • 821
  • 3
  • 9
  • 13

7 Answers7

70

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Java Devil
  • 10,629
  • 7
  • 33
  • 48
  • 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? – Euridice01 Nov 07 '14 at 19:35
  • @Euridice01 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`. – Java Devil Nov 09 '14 at 20:36
42

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.

YoYo
  • 9,157
  • 8
  • 57
  • 74
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));
5

For Java 8 and higher:

    String[] test = {"1", "2", "3", "4", "5"};
    int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();
Anton Saburov
  • 61
  • 1
  • 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()`. – YoYo Nov 22 '22 at 18:47
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));
  • Again, this just covers alternative forms of converting `String []` --> `int []`, not `String` --> `int []` (missing the delimiter parsing step). – YoYo Nov 22 '22 at 18:57
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
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
-3

Java has a method for this, "convertStringArrayToIntArray".

String numbers = sc.nextLine();
int[] intArray = convertStringArrayToIntArray(numbers.split(", "));
Alex
  • 1