user3019431
user3019431

Reputation: 11

How to convert a list item to int/double

I Made a list:

List<String> list = new ArrayList<String>();

String someData = "1234";

list.add(someData);

Is there any way to convert someData to int or double? The reason why i made it a String in the first place is that I had to input few informations (using loop) from a Scanner. Most of them is a String. And now I will need few of them to be int-like 'cause I want to do some math operations.

Upvotes: 0

Views: 545

Answers (3)

user2553189
user2553189

Reputation: 51

You can also use :

int flag=Integer.valueOf(someData);

And if you want to store it in an Integer list you can simply use :

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

list.add(Integer.valueOf(someData));

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

Use:

int i = Integer.parseInt(someData);

I don't really see what the List has to do with it? If you want a List of Integers, you could use:

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

String someData = "1234"; 
list.add(Integer.parseInt(someData));

Same goes for: List<Double> and Double.parseDouble().

Note that parseInt() can throw a NumberFormatException. Either make sure that this will not be the case, or handle it with a try-catch.

Upvotes: 4

Jack
Jack

Reputation: 133557

You can do as suggested by other answers or change how you scan data at the origin:

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

while (shouldScan) {
  int value = scanner.nextInt();
  list.add(value);
  ..
}

Mind that you should take care of catching a InputMismatchException exception in case the input format is wrong.

If you choose to use Integer.parseInt(string) you should take care of catching NumberFormatException instead.

Upvotes: 2

Related Questions