我是java的新手,我想问你一些帮助。我有一些数据存储在txt文件中,每行包含三个整数,以空格分隔。我想从文件中读取数据,然后将这些数据放在数组中进行进一步处理,如果满足某些条件(在我的情况下 - 第三个int大于50)。我阅读了一些关于如何读取文件或文件本身的行数的问题,但我似乎无法将它们结合起来使其工作。最新版本的代码如下所示:java-从文件读取数据以作进一步处理
public class readfile {
private Scanner x;
public void openFile(){
try{
x = new Scanner(new File("file.txt"));
}
catch (Exception e){
System.out.println("could not find file");
}
}
public void readFile() throws IOException{
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("file.txt")));
int i = lnr.getLineNumber();
int[] table1 = new int[i];
int[] table2 = new int[i];
while(x.hasNextInt()){
int a = x.nextInt();
int b = x.nextInt();
int c = x.nextInt();
for (int j=0; j< table1.length; j++)
{
if(c > 50)
{
table1[j]=a;
table2[j]=b;
}
}
}System.out.printf(" %d %d", table1, table2);
}
public void closeFile(){
x.close();
}
}
main位于另一个文件中。
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
try {
r.readFile();
}
catch (Exception IOException) {} //had to use this block or it wouldn't compile
r.closeFile();
}
当我使用%d上的printf方法我没有看到任何东西,当我使用%S我得到一些乱码的输出像
[[email protected] [[email protected]42
我应该怎么办,使其工作(即当c> 50时打印ab对)?
预先感谢任何帮助,对不起,如果这原来是一些公然明显的问题,但我真的跑出来的,关于如何提高这个想法:)
您正在告诉程序打印两个整数(%d),但传递了两个整数数组。 – CPerkins
其中x来自'while(x.hasNextInt()){'?你想先解析整个文件,然后打印数字,或者你想在飞行上一行一行吗?这可以通过更简单的方式来实现。此外,您需要打印数组索引中的值。不是数组本身:System.out.printf(“%d%d”,table1,table2); – happybuddha
如果此代码是独立的,那么也没有理由将对存储在表中。只需在你的'if'语句中打印它们。 – aquemini