我有一个字符串,例如“90 60 90” - 身体比例。我想从字符串中提取3个数字并将它们放入int数组中。像这样:
sizes[0] = 90;
sizes[1] = 60;
sizes[2] = 90;
也许有更优雅的方法解决这个问题,但我只能想到这种方式。如果您有更好的方法或者可以帮助修复这个问题,我会非常感激。当 j=2 且 a=' '时,循环停止。
public class Main {
public static void main(String[] args) {
String[] sizes = {"90 60 90", "90 70 60"};
// int[][] firstNumber = new int[sizes.length][3];
String firstNumber = "";
String secondNumber = "";
String thirdNumber = "";
int spaces = 0;
for (int i = 0; i < sizes.length; i++) {
int length = sizes[i].length();
for (int j = 0; j < length; j++) {
char a = sizes[j].charAt(j);
if (a != ' ' && spaces == 0) {
firstNumber += String.valueOf(a);
} else if (a != ' ' && spaces == 1) {
secondNumber += String.valueOf(a);
} else if (a != ' ' && spaces == 2) {
thirdNumber += String.valueOf(a);
} else if (a == ' ') {
spaces++;
}
}
}
System.out.println(firstNumber + secondNumber + thirdNumber);
}
}
感谢您。
Thank you.
String::split
? - midint[] array = Stream.of(string.split(" ")).mapToInt(Integer::parseInt).toArray();
- JB Nizet