2013-07-10 46 views
0

我是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对)?

预先感谢任何帮助,对不起,如果这原来是一些公然明显的问题,但我真的跑出来的,关于如何提高这个想法:)

+1

您正在告诉程序打印两个整数(%d),但传递了两个整数数组。 – CPerkins

+0

其中x来自'while(x.hasNextInt()){'?你想先解析整个文件,然后打印数字,或者你想在飞行上一行一行吗?这可以通过更简单的方式来实现。此外,您需要打印数组索引中的值。不是数组本身:System.out.printf(“%d%d”,table1,table2); – happybuddha

+0

如果此代码是独立的,那么也没有理由将对存储在表中。只需在你的'if'语句中打印它们。 – aquemini

回答

0

不能打印使用%d整个数组。循环访问阵列并分别打印每个值。

0

你得到乱码输出,因为您要打印的数组引用在printf()

对于个人价值观使用循环如..

for(int i:table1){ 
System.out.print(""+i) 
} 

OR

要对替代打印以下代码...

 if(c > 50) 
     { 
      table1[j]=a; 
      table2[j]=b; 
      System.out.printf("%d %d",a,b); 
     } 
0

您不能使用printf将数组格式化为int。如果要打印阵列的全部内容,请使用助手功能Arrays.toString(array)

E.g.

System.out.println(Arrays.toString(table1)); 
0

如果我得到你纠正你有一个像

12 33 54 
93 223 96 
74 743 4837 
234 324 12 

,如果第三个整数比你想存储的前两个50大的文件?

List<String> input = FileUtils.readLines(new File("file.txt"), Charset.forName("UTF-8")); 
HashMap<Integer, Integer> filtered = new HashMap<Integer, Integer>(); 

for (String current : input) { 
    String[] split = current.split(" "); 
    if (Integer.parseInt(split[2]) > 50) 
     filtered.put(Integer.parseInt(split[0]), Integer.parseInt(split[1])) 
} 
System.out.println(filtered); 
相关问题