[英]Reading from a text file with spaces and then putting into arrayList
我花了最后一周的时间试图弄清楚如何使这个愚蠢的代码起作用。 除了从我的文本文件读取之外,我已经设法使所有工作正常。 它可以读取一行中的单个整数,但是当给定一行包含多个由空格分隔的整数时,它会吓跑。 现在我已经去尝试修复它,并且代码甚至无法编译。 仅一行会引起问题。 我不擅长编码,所以我不知道从哪里开始。 是的,我已经在网上查询了此内容。 是的,我已经检查了论坛。 是的,我尝试了多种不同的方法来使它起作用。 :(
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);
感谢您的帮助! 我确定我只是缺少一些非常简单的东西...
您可以使用类似的Scanner(String)
while ((text = reader.readLine()) != null) {
Scanner scanner = new Scanner(text);
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
}
当然,可以通过使用try-with-resources
语句和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);
}
在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
}
在上面的代码中, personalArray将包含separated by space
每个单独的整数。 在for循环中,每个字符串都需要解析为整数,然后添加到列表中
尝试这个 :
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.