Harry
Harry

Reputation: 109

convert String to arraylist of integers using wrapper class

Im trying to write a program that takes a string of user inputs such as (5,6,7,8) and converts it to an arrayList of integers e.g. {5,6,7,8}. I'm having trouble figuring out my for loop. Any help would be awesome.

String userString = "";
ArrayList<Integer> userInts = new ArrayList<Integer>();

System.out.println("Enter integers seperated by commas.");
userString = in.nextLine();

for (int i = 0; i < userString.length(); i++) {
    userInts.add(new Integer(in.nextInt()));
}

Upvotes: 0

Views: 592

Answers (4)

Paul Murphy
Paul Murphy

Reputation: 106

Might I suggest a different input format? The first line of input will consist of an integer N. The next line contains N space separated integers.

5
3 20 602 3 1

The code for accepting this input in trivial, and you can use java.util.Scanner#nextInt() method to ensure you only read valid integer values.

This approach has the added benefit of validate the input as it is entered, rather than accepting a String and having to validate and parse it. The String approach presents so many edge cases which need to be handled.

Upvotes: 0

Debosmit Ray
Debosmit Ray

Reputation: 5413

I'm assuming the in is for a Scanner.

I don't see a condition to stop. I'll assume you want to keep doing this as long as you are happy.

List<Integer> arr = new ArrayList<Integer>();

while(in.hasNext()) 
    arr.add(in.nextInt());

And, say you know that you will get 10 numbers..

int count = 10;
while(count-- > 0) 
    arr.add(in.nextInt());

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

If your list consists of single-digit numbers, your approach could work, except you need to figure out how many digits there are in the string before allocating the result array.

If you are looking to process numbers with multiple digits, use String.split on the comma first. This would tell you how many numbers you need to allocate. After than go through the array of strings, and parse each number using Integer.parseInt method.

Note: I am intentionally not showing any code so that you wouldn't miss any fun coding this independently. It looks like you've got enough knowledge to complete this assignment by reading through the documentation.

Upvotes: 1

TheQAGuy
TheQAGuy

Reputation: 494

Lets look at the lines:

String userString = ""
int[] userInt = new int[userString.length()];

At this point in time userString.length() = 0 since it doesnt contain anything so this is the same as writing int[] userInt = new int[0] your instantiating an array that cant hold anything.

Also this is an array not an arrayList. An arrayList would look like

ArrayList<Integer> myList = new ArrayList()<Integer>;

Upvotes: 1

Related Questions