将字符串转换为 <整数>ArrayList

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


    } 

我正在尝试将一个数字字符串转换成数组,但它没有添加正确的值。我一直得到49和50。我想把用户输入的数字存储在ArrayList中。有人能帮忙吗?


1
这是因为它给你的是ASCII值,int y = num.charAt(x)-48 或者 Character.valueOf(num.charAt(x)),因为'0'的表示值是48,请参考:http://www.asciitable.com/。 - Nitin Dandriyal
@Thilo 和我的回答将会给你期望的结果。 - Naman Gala
5个回答

2
 int y = num.charAt(x);

这将为您提供字符的 Unicode 代码点,例如 A 的代码点为 65,0 的代码点为 48。

您可能想要:

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

0

你可以尝试使用:

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

替代

int y = num.charAt(x);

Integer.parseInt方法不适用于char作为方法参数。你的代码会产生编译错误。 - Naman Gala

0

您没有将输入转换为整数,因此JVM将其视为字符串。假设您的输入为1,则它会打印出“1”的49(ASCII等效)。

如果您想获得整数值,您需要使用解析函数进行解析。

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

Integer.parseInt方法不适用于char作为方法参数。你的代码会产生编译错误。 - Naman Gala

0

问题出在这段代码 int y = num.charAt(x); 上。你试图将返回的字符存储到 int 类型的变量中,所以它实际上是存储了字符的 ASCII 值。

你可以根据其他答案中的建议进行操作。


为了简化,您可以像这样重写您的代码。
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.
    }
}

注意:在将 char 作为方法参数时,Integer.valueOfInteger.parseInt 方法将无法给出正确的结果。你需要在这两种情况下传递 String 作为方法参数。

0
你正在将一个字符复制到一个整数中。你需要将它转换为一个整数值。
int y = Character.getNumericValue(num.charAt(x));

你的方法以整数作为输入(Integer valueOf(int i)),因此在这种情况下它将返回ASCII值。 - Naman Gala
请查看此链接 https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(java.lang.String),另外num.charAt(x)不会返回int。 - underdog
这是针对字符串(String)的,而不是字符(char)。在你的代码中,它正在传递字符,因此内部将调用valueOf(int i)方法,并将传递字符的ASCII值(由num.charAt(x)返回)作为方法参数。您可以通过执行代码进行检查。 - Naman Gala
你是对的,valueOf方法不能给出正确的值; - underdog
你的代码可以像这样工作:int y = Integer.valueOf(String.valueOf(num.charAt(x)));。请参考我回答这个问题时的注释部分。 - Naman Gala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接