-1

I am trying to read user input from a scanner into an integer array, I currently have this:

int [] arr1 = {Integer.parseInt(sc.nextLine().split(" "))};

But i am given the error

String[] cannot be converted to String

Any help would be much appreciated :)
1
  • Integer.parseInt converts single strings to integers. But you attempt to use it on a String[] (result of split), so multiple strings. You have to execute the method individually on all elements of the String[] and then collect the ints back to an array. Commented May 18, 2020 at 5:55

1 Answer 1

1
sc.nextLine().split(" ") //This returns String[]
int a = Integer.parseInt("") //Integer.parseInt requires one String param.

Try below code:

String input = sc.nextLine();
String[] inputs = input.split(" ");

List<Integer> ints = Arrays.stream(inputs).
map(Integer::parseInt).collect(Collectors.toList());

Check the document:
API: Integer.parseInt String.split()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.