0

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.

webermaster
  • 209
  • 1
  • 13
user3019431
  • 11
  • 1
  • 4

3 Answers3

4

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.

Martijn Courteaux
  • 63,780
  • 43
  • 187
  • 279
  • 3
    Worth noting that `parseInt` can throw a `NumberFormatException` which you can catch and handle to your convenience. http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String) – DSquare Dec 30 '13 at 18:50
  • And while we're at it, there's also `Double.parseDouble()`, and DSquare's note also applies here too. – Dennis Meng Dec 30 '13 at 18:55
2

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.

Jack
  • 125,196
  • 27
  • 216
  • 324
  • Just in case OP *does* change how he uses the scanner, it might be good to point out http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint just in case – Dennis Meng Dec 30 '13 at 18:57
0

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));