Issue
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
Solution
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.
Split your String variable into a String-Array
String numbers = "1, 2, 3, 4, 5"; String[] numbersSplitted = numbers.split(", ");
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]); }
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!
Answered By - Manifest Man
Answer Checked By - Mildred Charles (JavaFixing Admin)