2014-09-30 41 views
0

我试图为我们的项目建立一个工资系统,完成GUI和事件处理程序,但我被卡在文件处理。如何从阵列中打印特定的行?

我有一个文本文件,它看起来财产以后这样

1 Miguel 491 
2 Jasper 323 
3 Will 363 

我想要检索的文本 输出

1 Miguel 491 

下面一行是我的代码:

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 
import javax.swing.*; 

import java.awt.Label; import java.awt.event.*; 

public class Main { public class panels extends JFrame{ 





     } 
    public static void main(String[] args) {   

     JFrame frame = new JFrame("Payroll by Miggy"); 
     frame.setSize(400,300); 
     frame.setLocationRelativeTo(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
     Label idlabel;      // Declare an Label instance called lblInput 
     idlabel = new Label("Enter ID"); 
     JButton jbtok = new JButton("Ok"); 

     frame.add(jbtok); 

     try { 
      File f = new File("C:/Users/MIGXTREME/Desktop/Employee.txt"); 
      Scanner sc = new Scanner(f); 

      List<Employee> people = new ArrayList<Employee>(); 

      while(sc.hasNextLine()){ 
       String line = sc.nextLine(); 
       String[] details = line.split(" "); 
       int Id = Integer.parseInt(details[0]); 
       String name = details[1]; 
       int rate = Integer.parseInt(details[2]); 
       Employee p = new Employee(Id, name, rate); 
       people.add(p); 
      } 

      for(Employee p: people){ 
       System.out.println(p.toString()); 
      } 

     } catch (FileNotFoundException e) {   
      e.printStackTrace(); 
     } 
    } } 

class Employee{ 

    private int Id; 
    private String name; 
    private int rate; 

    public Employee(int Id, String name, int rate){ 
     this.Id = Id; 
     this.setName(name); 
     this.rate = rate; 
    } 

    public int getId() { 
    return Id; } 


public void setGender(int Id) { 
    this.Id = Id; } 


public void setName(String name) { 
    this.name = name; } 


public String getName() { 
    return name; } 


public int getrate() { 
    return rate; } 


public void setrate(int rate) { 
    this.rate = rate; } 

public String toString(){ 
    return this.Id + " " + this.name + " " + this.rate*4; } } 
+0

所以你面对什么问题? – 2014-09-30 11:11:54

+0

你能解释一下怎么回事?你做了什么没有奏效?另外,什么是抛出一个错误?你的文本文件是如何写入的?每行1人?或者更多?你需要给我们更多的细节,所以我们可以尝试帮助你,而不是为你做的工作。 – Softy 2014-09-30 11:13:21

+0

实际上没有错误,我只是想知道如何从文本文件中打印特定的行而不是所有的行.. – 2014-09-30 11:16:19

回答

0

查看RandomAccessFile类。这将有助于非顺序地遍历文件。

0

只是做:

for(Employee p: people){ 
    if(p.name.equals("Miguel")){ 
     System.out.println(p.toString()); 
     break; 
    } 
}