3

I have referenced this in an attempt to convert my list to an array, but I can't seem to get it to work. Here is what I have:

    int values[] = Arrays.asList(str.replaceAll("[^-?0-9]+", " ").trim().split(" ")).toArray();

The error that I am getting (type mismatch) is stating that I should change the type of values[] from int to object

The end result should just be an array of numbers. Example: a-9000xyz89 would be an array with [-9000, 89] as the values

Community
  • 1
  • 1
bob dylan
  • 607
  • 9
  • 22

2 Answers2

3

String#split will return String[] and not int[]. You have to iterate over String[] and create int[]. Moreover, you don't need to convert array to list with Arrays.asList.

For example,

String str = "1 2 3 4";
String arr[] = str.split(" ");
int[] ans = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
    ans[i] = Integer.parseInt(arr[i]);
}
System.out.println(Arrays.toString(ans));

OUTPUT

[1, 2, 3, 4]

EDIT

I am getting the same error when I remove the toArray() and when I change values[] to a String[]. String values[] = Arrays.asList(question.replaceAll("[^-?0-9]+", " ").trim().split(" "));

Note that Arrays.asList in your case will return List<String> but type of values is String[].

You can directly store result of split in values,

String values[] = question.replaceAll("[^-?0-9]+", " ").trim().split(" ");
ΔȺȾΔ
  • 21,571
  • 10
  • 52
  • 80
  • I am getting the same error when I remove the toArray() and when I change values[] to a String[]. String values[] = Arrays.asList(question.replaceAll("[^-?0-9]+", " ").trim().split(" ")); – bob dylan Dec 31 '15 at 02:02
  • Thanks for your reply, but that, for my case will not work because I do not want to separate every number from each other; I only want to separate the numbers from the string. So if I had a string = "xyq123x1" it should return [123, 1] instead of [1, 2, 3, 1]. – bob dylan Dec 31 '15 at 02:08
0

Following will work for Java 8

int[] values = Arrays.stream(str.replaceAll("[^-?0-9]+", " ").trim().split(" ")).mapToInt(Integer::parseInt).toArray();

Note - [^-?0-9]+ does not support strings such as a-90-00xyz89 or a-9000x-yz89 because it will produce non-integers

hmc
  • 83
  • 9