javacharat

charAt() returning weird values


I am trying to make program that convert number to words but when I use charAt(0) to get the value of index 0 its returning me strange values

 import java.util.Scanner;

public class numToWord {
    public static   void main(String[] args) {

        String[] digit = {"Zero","One ","Two", "Three ","Four ","Five ","Six ", "Seven ", "Eight ", "Nine" };
        Scanner sc  = new Scanner(System.in);
        String strNum = sc.next(); //input 123
        int intnum = Integer.valueOf(strNum.charAt(0));
        System.out.println(intnum);
        System.out.println(digit[intnum]);
        //output 49

    }
}

example input 123 output 49

Input Output:


Solution

  • valueOf() is used for string conversion not for char type.

    If you want to convert a char value to an integer using valueOf() it's always return the ASCII value of it. Use Character.getNumericValue() to solve this problem.

    import java.util.Scanner;
    public class numToWord{
        public static   void main(String[] args) {
            String[] digit = {"Zero","One ","Two", "Three ","Four ","Five ","Six ", "Seven ", "Eight ", "Nine" };
            Scanner sc  = new Scanner(System.in);
            String strNum = sc.next();
            //int intnum = Integer.valueOf(strNum.charAt(0));
            int intnum = Character.getNumericValue(strNum.charAt(0));
            System.out.println(intnum);
            System.out.println(digit[intnum]);
        }
    }