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

2 Answers 2

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(" ");
Sign up to request clarification or add additional context in comments.

2 Comments

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(" "));
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].
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.