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?

+3


source to share


5 answers


 int y = num.charAt(x);

      

This will give you the Unicode code for the character. Like 65 for A or 48 for 0.



You probably want

 int y = Integer.parseInt(num.substring(x, x+1));

      

+2


source


You may try:

int y = Integer.parseInt(num.charAt(x));

      



instead

int y = num.charAt(x);

      

0


source


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

      

0


source


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.

0


source


You are copying char to int. You need to convert it to int value.

int y = Character.getNumericValue(num.charAt(x));

      

0


source







All Articles