Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 786
duck chillings Avatar asked Feb 16 '26 09:02

duck chillings


1 Answers

 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));
like image 62
Thilo Avatar answered Feb 17 '26 21:02

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!