我有一个String数组
String[] list = new String[]{"2","A","B","1","C","3","D","E","F"}
请注意,数组的第一个元素是2。 我会做的 -
int n = Integer.parseInt(list[0]);
问题是,我需要一个循环来完成数组。我似乎无法解析它而没有给我NumberFormatException
错误。另外,请注意,如果数字是2,它将排列接下来的2个元素(可能是随机的),然后是空格。
1:A
2:B
3:-empty -
4:D
5:E
6:F
7:-empty -
8:C
答案 0 :(得分:0)
遍历数组并检查所选字符是否为数字。如果是数字使用parseInt。
这是一个如何识别数字的教程。 What is the best way to tell if a character is a letter or number in Java without using regexes?
祝你好运。答案 1 :(得分:0)
迭代数组时,在循环中使用try / catch语句。
这是一个简短的例子:
for(int i = 0; i < list.length; i++) {
try {
int n = Integer.parseInt(list[i]);
// do whatever you need to do with n here
}
catch (NumberFormatException nfex) {
// do something else with the current element if need be
}
}
答案 2 :(得分:0)
for(String hexNbr : list)
{
System.out.println("Next number is " + Integer.parseInt(hexNbr, 16);
}
您的输入是十六进制,因此您必须使用parseInt(String,radix)。
答案 3 :(得分:0)
算法很简单。
进展如下:
Start: "2","A","B","1","C","3","D","E","F"
N = 2
Shift: "A","B","B","1","C","3","D","E","F"
Empty: "A","B","-","1","C","3","D","E","F"
N = 1
Shift: "A","B","-","C","C","3","D","E","F"
Empty: "A","B","-","C","-","3","D","E","F"
N = 3
Shift: "A","B","-","C","-","D","E","F","F"
Empty: "A","B","-","C","-","D","E","F","-"
代码的
String[] list = {"2","A","B","1","C","3","D","E","F"};
for (int i = 0; i < list.length; ) {
int len = Integer.parseInt(list[i]);
System.arraycopy(list, i + 1, list, i, len);
list[i + len] = "-empty-";
i += len + 1;
}
for (String value : list)
System.out.println(value);
输出
A
B
-empty-
C
-empty-
D
E
F
-empty-