我在设置并行数组时遇到问题。如何读取文本文件并将其打印在编译器输出窗口中? stuff.txt包含以下数据:
Sue 57
Chad 52
Ram 43
希望有人可以提供帮助。到目前为止,这是我的代码:
import java.io.*;
import java.util.*;
public class nameAge
{
public static void main(String[] args) throws FileNotFoundException
{
String name[] = new String[3];
int ages[] = new int[3];
Scanner inFile = new Scanner(new File("stuff.txt"));
int i = 0;
while (inFile.hasNextLine())
{
name[i] = inFile.next();
ages[i] = inFile.nextInt();
}
System.out.println(name[i] + " " + ages[i] );
}
}
答案 0 :(得分:2)
我建议您先从Arrays更改为ArrayList,因为不应假设文件大小。
我会改为:
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> ages = new ArrayList<Integer>();
然后,你的while循环可以做到这一点:
while(lineScanner.hasNext()){
names.add(lineScanner.next());
ages.add(lineScanner.nextInt());
}
然后,您可以通过那些(理论上)长度应该相同的ArrayLists设置for循环,但也许你可以做一些错误检查,如下所示:
if(names.size() != ages.size()){
System.out.println("Something wen't wrong - the number of names and ages are not equal.");
} else{
for(int i = 0; i < names.size(); i++){
System.out.println(names.get(i) + " " + ages.get(i));
}
}
有些东西可能需要调整,因为我没有打开IDE,但希望能在正确的位置推进。
答案 1 :(得分:0)
尝试:
while (inFile.hasNextLine()) {
String line = inFile.nextLine();
Scanner lineScanner = new Scanner(line);
while(lineScanner.hasNext()) {
name[i] = lineScanner.next();
ages[i] = lineScanner.nextInt();
i++;
}
}