我的问题是 - 如何将字符串ArrayList转换为整数ArrayList?
我的数字后面带有 °
EX: 352°
。如果我将它们放入 Integer ArrayList 中,它将无法识别这些数字。为了解决这个问题,我将它们放入 String ArrayList 中,然后它们被识别。
我想将该字符串数组列表转换回整数数组列表。那么我该如何实现这一目标呢?
这是我到目前为止的代码。我想将 ArrayString 转换为 Int Arraylist。
// Read text in txt file.
Scanner ReadFile = new Scanner(new File("F:\\test.txt"));
// Creates an arraylist named ArrayString
ArrayList<String> ArrayString = new ArrayList<String>();
// This will add the text of the txt file to the arraylist.
while (ReadFile.hasNextLine()) {
ArrayString.add(ReadFile.nextLine());
}
ReadFile.close();
// Displays the arraystring.
System.out.println(ArrayString);
提前致谢
迭戈
PS:抱歉,如果我不完全清楚,但英语不是我的主要语言。而且我对 Java 还很陌生。
最佳答案
您可以使用 String.replaceAll
替换任何要忽略的字符(在本例中为 °
):
"somestring°".replaceAll("°",""); // gives "sometring"
或者您可以使用String.substring
删除最后一个字符:
"somestring°".substring(0, "somestring".length() - 1); // gives "somestring"
其中之一应该适合您的情况。
现在剩下的就是使用 Integer.parseInt
即时解析输入:
ArrayList<Integer> arrayInts = new ArrayList<Integer>();
while (ReadFile.hasNextLine()) {
String input = ReadFile.nextLine();
try {
// try and parse a number from the input. Removes trailing `°`
arrayInts.add(Integer.parseInt(input.replaceAll("°","")));
} catch (NumberFormatException nfe){
System.err.println("'" + input + "' is not a number!");
}
}
您可以添加自己的处理方式来处理输入不是实际数字的情况。
关于JAVA:如何将字符串ArrayList转换为整数ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32015342/