我在上周试图弄清楚如何使这个愚蠢的代码工作。除了从我的文本文件中读取外,我已设法让一切工作正常。它可以读取一行上的单个整数,但是当给定一个由空格分隔的多个整数的行时,它会变得怪异。现在我已经离开并尝试修复它,代码甚至不再编译。只有一行导致问题。 我不擅长编码,所以我不知道从哪里开始。是的,我在网上看了这个。是的,我查了一下论坛。是的,我尝试了多种不同的方法来完成这项工作.... 我该如何解决?? :(
ArrayList<Integer> list = new ArrayList<Integer>();
// the above line is in a different method in the same class, but it's relevant here
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null)
{
// I want the following line to read "218 150 500 330", and to store each individual integer into the list. I don't know why it won't work :(
list.add(Integer.parseInt(src.next().trim()));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//print out the list
System.out.println(list);
谢谢你的帮助!我确信我只是错过了一些非常简单的事情......
答案 0 :(得分:1)
您可以使用Scanner(String)
之类的
while ((text = reader.readLine()) != null) {
Scanner scanner = new Scanner(text);
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
}
当然,使用try-with-resources
Statement和diamond operator
以及Scanner(File)
之类的
public static void main(String[] args) {
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
List<Integer> list = new ArrayList<>();
try (Scanner scanner = new Scanner(file);) {
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
} catch (Exception e) {
e.printStackTrace();
}
// print out the list
System.out.println(list);
}
答案 1 :(得分:0)
在 while 循环
中进行此操作String[] individualArray = text.split(" ");//note space
for(String individual:individualArray){
yourList.add(individual);//You need to parse it to integer here as you have already done
}
在上面的代码中, individualArray 将包含separated by space
的每个单独的整数。在 for循环内,每个字符串需要解析为整数,然后添加到列表中
答案 2 :(得分:0)
试试这个:
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null)
{
// you need only this for loop in you code.
for (String value : text.split(" ")) { // get list of integer
if(!value.equals("")) // ignore space
list.add(Integer.parseInt(value)); // add to list
}
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
// print out the list
System.out.println(list);
}