[英](Java) Convert a string of numbers to an array of ints
我正在尝试将一个由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);
}
知道我该怎么办吗?
这个怎么样:
for (int count = 0; count < userInput.length; ++count)
intArray[count] = userInput.charAt(count)-'0';
我认为在这里有点令人困惑的是,可以将整数和字符相互插入。 字符 “ 1”的int值实际上是49。
这是一个解决方案:
for (int i = 0; i < 16; i++) {
intArray[i] = Integer.valueOf(userInput.substring(i, i + 1));
}
substring方法将字符串的一部分作为另一个字符串而不是字符返回,并且可以将其解析为int。
一些技巧:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.