我的任务有问题。
我的工作是
- 从文件中获取一个
字符串
(源文件中是一行中的数字,用空格分隔) - 用空格分割该字符串
- 然后将每个
String
解析为int
- 最后对它们使用 bubbleSort。
我被困在解析上,不知道该怎么做。
代码 atm 看起来像这样:
public class Main
{
public static void main(String[] args) throws IOException
{
String numbers = new String(Files.readAllBytes(Paths.get("C:\\README.txt")));
String s[] = numbers.split(" ");
for (String element : s)
{
System.out.println(element);
}
}
}
我尝试使用扫描仪读取字符串数字,然后循环它进行 parseInt,但对我不起作用。
最佳答案
您正在寻找的方法是Integer#parseInt()
使用Java 8时,您可以使用Stream API如下:
final List<Integer> intList = new LinkedList<>();
try {
Files.lines(Paths.get("path\\to\\yourFile.txt"))
.map(line -> line.split(" "))
.flatMap(Stream::of)
.map(Integer::parseInt)
.forEach(intList::add);
} catch (IOException ex) {
ex.printStackTrace();
}
没有流:
final List<Integer> intList = new LinkedList<>();
try {
for (String line : Files.readAllLines(Paths.get("path\\to\\yourFile.txt"))) {
for (String numberLiteral : line.split(" ")) {
intList.add(Integer.parseInt(numberLiteral));
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
关于java - 多任务: parse space-separated integers from a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26670288/