charAt() 返回奇怪的值

charAt() returning weird values

我正在尝试编写将数字转换为单词的程序,但是当我使用 charAt(0) 获取索引 0 的值时,它返回了奇怪的值

 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

    }
}

示例输入 123 输出 49

Input Output:

您当前正在读取输入的第一个字符的 ascii 值。此外,您的数字映射中有空格。您想要做的是解析每个数字并获取映射。像,

String[] digit = { "Zero", "One", "Two", "Three", "Four", 
        "Five", "Six", "Seven", "Eight", "Nine" };
Scanner sc  = new Scanner(System.in);
String strNum = sc.next();
for (int i = 0; i < strNum.length(); i++) {
    if (i != 0) {
        System.out.print(" ");
    }
    int v = Character.digit(strNum.charAt(i), 10); // strNum.charAt(i) - '0'
    System.out.print(digit[v]);
}
System.out.println();

valueOf() 用于字符串转换而不是 char 类型。

如果您想使用 valueOf()char 值转换为 integer它总是 return 的 ASCII value。使用Character.getNumericValue()来解决这个问题。

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

查一下 ASCII 是什么。

字符 '1' 映射到 ASCII 图表上的十进制值 49