2015-09-20 71 views
0

我无法弄清楚如何将这个带有数字的txt文件放入数组中,我能够读取并打印屏幕,但我需要能够组织数字并删除重复项。这是我的代码看起来像到目前为止从一个文件中读取数字并创建一个数组(java)

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 

public class File { 
public static void main(String[] args) { 
String filename = "C:/input.txt"; 

File rfe = new File(); 
rfe.readFile(filename); 
} 

private void readFile(String name) { 
String input; 

    try (BufferedReader reader = new BufferedReader(new FileReader(name))) { 

    while((input = reader.readLine()) != null) { 
     System.out.format(input); // Display the line on the monitor 
    } 
} 
catch(FileNotFoundException fnfe) { 

} 
catch(IOException ioe) { 

} 
catch(Exception ex) { // Not required, but a good practice 

} 


} 
} 
+1

输入的来源真的很重要吗?你的问题似乎是[如何]组织数字并删除重复项。你做了什么来实现这一目标? –

+0

只需将它们添加到'Set'。重复将自动消除 – Paul

+0

数组不是“Java中的动态数据结构”,因此不能“删除元素”。你期望输出什么?你会得到什么输出? –

回答

0

我会建议使用ArrayList而不是数组。

对于数组,您必须先解析列表并计算行数,然后才能对其进行初始化。 ArrayList更灵活,因为您无需声明将添加多少个值。

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

public class File { 

private List<Integer> data = new ArrayList<Integer>(); //Create ArrayList 

public static void main(String[] args) { 
    String filename = "C:/input.txt"; 

    File rfe = new File(); 
    rfe.readFile(filename); 
} 

private void readFile(String name) { 
    String input; 

    try (BufferedReader reader = new BufferedReader(new FileReader(name))) { 

     while((input = reader.readLine()) != null) { 
      data.add(Integer.parseInt(input));//Add each parsed number to the arraylist 
      System.out.println(input); // Display the line on the monitor 
     } 
    } 
    catch(FileNotFoundException fnfe) { 

    } 
    catch(IOException ioe) { 

    } 
    catch(Exception ex) { // Not required, but a good practice 
     ex.printstacktrace(); //Usually good for general handling 
    } 

} 
} 
+1

谢谢!我正在教自己如何编写代码,所以这真的很有帮助! –

+0

没问题,快乐编码! –

相关问题