简体   繁体   中英

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM