String input to <Integer> ArrayList
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sequence of numbers ending with 0.");
ArrayList<Integer> list = new ArrayList<Integer>();
String num = scan.nextLine();
for(int x=0; x < num.length(); x++){
System.out.println(num.charAt(x));
int y = num.charAt(x);
System.out.println(y);
list.add(y);
System.out.println(list);
}
I am trying to pass a string of numbers to an array. This is not adding the right ox. I keep getting 49 and 50. I want to store the numbers that the user enters into the ArrayList. Can anyone help?
source to share
You are not converting input to Integer, so the JVM accepts them as a string. Assuming that when you enter 1, you are typing 49 (ASCII equivalent) "1".
If you want to get the integral values ββyou need to parse it with
int y = Integer.parseInt(num.charAt(x));
System.out.println(y);
list.add(y);
System.out.println(list);
source to share
How this code int y = num.charAt(x);
creates the problem. When you try to store the returned character into an int value, it stores the ASCII value of the character.
You can go with suggestions in other answers.
For simplicity, you can rewrite your code as follows.
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sequence of numbers ending with 0.");
ArrayList<Integer> list = new ArrayList<Integer>();
String num = scan.nextLine();
char[] charArray = num.toCharArray();
for (char c : charArray) {
if (Character.isDigit(c)) {
int y = Character.getNumericValue(c);
System.out.println(y);
list.add(y);
System.out.println(list);
} else {
// you can throw exception or avoid this value.
}
}
Note. Integer.valueOf
and Integer.parseInt
will not give the correct result for char as a method argument. You need to pass String as method argument in both cases.
source to share