duck chillings
duck chillings

Reputation: 31

Casting string into <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);


    } 

Im trying to cast a string of numbers into a array. Its not adding the correct vaule. I keep getting 49 and 50. I want to store the numbers the user enters into the ArrayList. Can someone help?

Upvotes: 3

Views: 269

Answers (5)

techPackets
techPackets

Reputation: 4516

You are copying a char into an int. You need to convert it into an int value.

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

Upvotes: 0

Naman Gala
Naman Gala

Reputation: 4692

As this code int y = num.charAt(x); is creating the problem. As you are trying to store returned character into int value, so it is storing ASCII value of the character.

You can go with the suggestions in other answers.


For the simplicity, you can rewrite your code like this.

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 proper result for char as a method argument. You need to pass String as a method argument in both the cases.

Upvotes: 0

Saurabh Jhunjhunwala
Saurabh Jhunjhunwala

Reputation: 2922

You are not converting the input to Integer, thus JVM is taking them as string. Assuming you are 1 as you input it is printing 49 (ASCII equivalent) of "1".

If you want to get the integral values, you need to parse it using

int y = Integer.parseInt(num.charAt(x));
System.out.println(y);
list.add(y);
System.out.println(list);

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172518

You can try to use:

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

instead of

int y = num.charAt(x);

Upvotes: 0

Thilo
Thilo

Reputation: 262684

 int y = num.charAt(x);

That will give you the Unicode codepoint for the character. Like 65 for A or 48 for 0.

You probablay want

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

Upvotes: 2

Related Questions