以下代码我花了几个小时使用多种不同的策略从String st中提取整数值并将它们放入自己的int变量中。
这是一个测试程序,我正在进行的实际作业要求我构建一个类,使另一个程序(program5)正确运行。 program5生成的字符串可能只包含三个整数,但所有字符都将由一个空格分隔。由于赋值的具体细节,我不允许使用数组或正则表达式,因为我们没有在课堂上覆盖它们。
到目前为止,我甚至无法打印出我测试字符串中的所有三个整数。如果有人发现我的语法错误或逻辑问题,请告诉我!
public class test {
public static void main(String[] args){
String st = "10 9 8 7 6";
int score;
int indexCheck = 0;
String subSt;
for(int i=0; i <= st.length(); i++)
{
if(st.indexOf(' ') != -1)
{
if(st.charAt(i) == ' ')
{
subSt = st.substring(indexCheck, i);
score = Integer.parseInt(subSt);
indexCheck = st.indexOf(i);
System.out.println(score);
}
}
else
{
subSt = st.substring(st.lastIndexOf(" "));
score = Integer.parseInt(subSt);
System.out.println(score);
}
}
}
}
答案 0 :(得分:2)
使用st.split(" ")
获取存储按空格分割的字符串的String[]
,然后在每个索引上使用Integer.parseInt(array[0])
将其转换为int
。
实施例
String str = "123 456 789";
String[] numbers = str.split(" ");
int[] ints = new int[numbers.length];
for(int c = 0; c < numbers.length; c++) ints[c] = Integer.parseInt(numbers[c]);