Does the split function in Processing and in Eclipse exist in actual Java?

Viewed 150

Does the .split() function even exist? When I type:

public class Main {
    public static void main(String[] args) {
        String numbers = "1, 2, 3, 4, 5";
        int[] numbers2 = (int[]) numbers.split(", ");
    
        System.out.println(numbers2);
    }
}

It says:

Main.java:4: error: incompatible types: String[] cannot be converted to int[]
    int[] numbers2 = (int[]) numbers.split(", ");
                                          ^
1 error
2 Answers

numbers.split(", ") returns a String array. You can use the following to map a String array to an int array.

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

yes the method String[] split​(String regex) for reference type String exists, here is the reference https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String) for Java SE 11.

But you are trying to cast a variable of reference type String to an array of primitive int-type, which cannot be achieved directly in Java without parsing.

  1. Split your String variable into a String-Array

    String numbers = "1, 2, 3, 4, 5";
    String[] numbersSplitted = numbers.split(", ");
    
  2. Parse your String-Array to an int-Array

    int [] numbersParsed = new int[numbersSplitted.length];
    for(int i = 0; i < numbersSplitted.length; i++){
        numbersParsed[i] = Integer.parseInt(numbersSplitted[i]);
    }
    
  3. Print the parsed array or each element of the parsed array out to the console

    System.out.println(Arrays.toString(numbersParsed));

     // or print each element of the parsed array
    
     for (int val : numbersParsed) {
         System.out.println(val);
     }
    

Hopefully, this will help out!

Related