+ 1
How do you convert a String array list to an integer array list in Java?
import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; /** This program demonstrates how to take input for an ArrayList and sums the contents if the numbers in an even index are odd as well as those numbers in an odd index if they are even. */ public class Problem2 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); ArrayList<String> nums = new ArrayList<>(); ArrayList<Integer> nums2 = new ArrayList<>(); int sum = 0; System.out.println("Enter numbers to add to the list or -1 to quit: "); nums.add(keyboard.nextLine()); System.out.println(nums + " -> " + sum); } }
2 Answers
+ 5
So, your arraylist nums contains only 1 string in any input
Then you should use only String nums
How to divide string into integers:
String[] arrnums = nums.split(" ");
for(int i=0; i<arrnums.length; ++i){
nums2.add(Integer.parseInt(arrnums[i]));
}
0
Thank you very much, it worked. :)