gpt4 book ai didi

java - 从字符串中解析整数android java

转载 作者:行者123 更新时间:2023-12-02 08:11:28 27 4
gpt4 key购买 nike

嗨,我得到了以下代码,我用它从字符串中获取一些整数。如果索引处的字符是“-”,我可以通过将字符串与下一个数字组合来成功分离负整数和正整数,并且我可以将数字放入整数数组中...

   //degree is the String i parse

String together="";
int[] info=new int[degree.length()];
int counter=0;

for (int i1 = 0; i1 < degree.length(); i1++) {

if (Character.isSpace(degree.charAt(i1))==false){
if (Character.toString(degree.charAt(i1)).equalsIgnoreCase("-")){
together="-";
i1++;

}
together = together + Character.toString(degree.charAt(i1));

info[counter]=Integer.parseInt(together);
}
else if (Character.isSpace(degree.charAt(i1))==true){
together ="";
counter++;
}

但是我遇到了这个奇怪的问题....字符串看起来完全像“4 -4 90 70 40 20 0 -12”,并且代码解析并将整数放入数组中,仅指向我的意思是“0”数字除了最后一个“-12”数字之外,我将所有负数和正数放入数组中......有什么想法吗?

最佳答案

我认为您的问题有一个更简单的解决方案:

// First split the input String into an array,
// each element containing a String to be parse as an int
String[] intsToParse = degree.split(" ");

int[] info = new int[intsToParse.length];

// Now just parse each part in turn
for (int i = 0; i < info.length; i++)
{
info[i] = Integer.parseInt(intsToParse[i]);
}

关于java - 从字符串中解析整数android java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7360518/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com