0

我正在尝试将一个填充有 16 位数字的字符串转换为一个整数数组,其中每个索引都保存其在字符串中相应索引的数字。我正在编写一个程序,我需要对字符串中的单个整数进行数学运算,但我尝试过的所有方法似乎都不起作用。我也不能按字符分割,因为用户正在输入数字。

这是我尝试过的。

//Directly converting from char to int 
//(returns different values like 49 instead of 1?)    
//I also tried converting to an array of char, which worked, 
//but then when I converted
//the array of char to an array of ints, it still gave me weird numbers.

for (int count = 0; count <=15; count++)
{
   intArray[count] = UserInput.charAt(count);
}

//Converting the string to an int and then using division to grab each digit,
//but it throws the following error (perhaps it's too long?):
// "java.lang.NumberFormatException: For input string: "1234567890123456""

int varX = Integer.parseInt(UserInput);
int varY = 1;
for (count=0; count<=15; count++)
{
    intArray[count]= (varX / varY * 10);
}

知道我应该怎么做吗?

4

2 回答 2

5

这个怎么样:

for (int count = 0; count < userInput.length; ++count)
   intArray[count] = userInput.charAt(count)-'0';
于 2012-05-13T11:30:36.323 回答
-1

我认为这里有点令人困惑的是整数和字符可以相互插入。字符'1'的 int 值实际上是 49。

这是一个解决方案:

for (int i = 0; i < 16; i++) {
    intArray[i] = Integer.valueOf(userInput.substring(i, i + 1));
}

substring 方法将字符串的一部分作为另一个字符串返回,而不是字符,并且可以将其解析为 int。

一些技巧:

  • 我将 <= 15 更改为 < 16。这是对流,它会告诉您实际上将通过多少循环交互 (16)
  • 我将“计数”更改为“我”。另一个约定...
于 2012-05-13T11:46:34.453 回答