1

For example, if i input the line " 0 3 5 2 5 5 ", how do i turn the numbers into an array, containing "0, 3, 5, 2, 5, 5"

Right now, i use this code, but it doesnt work.


        System.out.println("How many numbers?");
        int numbers = in.nextInt();

        System.out.println("write in the following way:");
        System.out.println("num1 num2 num3 ");
        String msg = in.next() + "  ";

        int[] list = omv(numbers, msg);
        for (int i = 0; i < numbers; i++){
            System.out.println(list[i]);
        }

    }

    static int[] omv(int num, String msd) {

        int separat1 = 0;
        int separatee2 = 0;
        int[] list = new int[antal - 1];
        String letter;
        int letterint;
        int length = meddelande.length();

        while (separate1 >= length || separate1 != -1 || separate2 >= length || separate2 != -1) {

            separate1 = msg.indexOf(' ', separate2);
            // Hittar nästa mellanslag

            letter = msg.substring(separate2, separate1);
            // ERROR HERE

            letterint = Integer.parseInt(letter);


            list[i] = letterint;

            separate2 = (separate1 + 1);

            i++;

        }
        return list;
    }

This doesnt work and it gives an error on letter = msg.substring(separate2, separate1) i havent found a way to fix this, please help, thanks a lot

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
hz1212
  • 29
  • 1

3 Answers3

3

If you are using Java-8 you can use :

int[] ints = Arrays.stream(" 0 3 5 2 5 5 ".trim().split("\\s+"))
        .mapToInt(Integer::valueOf)
        .toArray();
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
2

If you don't have Java 8 or higher, you can do it the classic way:

public static void main(String[] args) {
    String numberString = " 0 3 5 2 5 5 ";
    // trim and split the String by an arbitrary amount of whitespaces
    String[] stringNumbers = numberString.trim().split("\\s+");
    // create an array of integers with the same size
    int[] numbers = new int[stringNumbers.length];

    // parse each String-number to int and put it into the int array
    for (int i = 0; i < numbers.length; i++) {
        numbers[i] = Integer.valueOf(stringNumbers[i]);
    }

    // print all the numbers from the int array
    for (int num : numbers) {
        System.out.println(num);
    }
}

Output:

0
3
5
2
5
5
deHaar
  • 17,687
  • 10
  • 38
  • 51
1

If your string have spaces you can use

String numbers="0 3 5 2 5 5";
String numbersArr[] = numbers.split(" ");

so you gonna have an array

So if you want to have a number array you can do

int newNumbersArr[] = new int[numbersArr.length];
for(int i = 0; i<numbersArr.length; i++){
  newNumbersArr[i] = Integer.valueOf(numbersArr[i]);
}
Fabio Assuncao
  • 624
  • 4
  • 12