如何创建一个void方法来读取文件并将信息存储到数组中,然后将该方法中的文本显示到JTextArea中



所以我创建了一个读取文件的方法,对于该文本文件中的每一行,该方法都将它们输入到一个数组中。现在,我正试图弄清楚如何将整个方法(readFile方法)显示到我的JTextArea中。请帮忙?

import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
import java.io.* ;
import java.util.Scanner; 

public class NameViewer {
JTextField nameTF;
JTextArea displayArea;
NameRecord[] nameList ;
public static void main( String[] arg ) {
    NameViewer app = new NameViewer() ;
}
public NameViewer() {
    JFrame frame = new JFrame( "Name Surfer" ) ;
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ) ;
    JPanel mainPanel = new JPanel() ;
    mainPanel.setLayout( new BorderLayout() ) ;
    displayArea = new JTextArea(25, 50) ;
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane( displayArea ) ;
    mainPanel.add( BorderLayout.CENTER, scrollPane ) ;
    displayArea.setText(readFile());
    JPanel controlPanel = new JPanel() ;
    controlPanel.setLayout( new GridLayout(1, 3) ) ;
    nameTF = new JTextField( 7 ) ;
    controlPanel.add( nameTF ) ;
    JButton find = new JButton(" Find " );
    controlPanel.add(find) ;
    find.addActionListener( new Listener());
    JButton match = new JButton(" Match " );
    controlPanel.add(match) ;
    match.addActionListener( new Listener());
    mainPanel.add( BorderLayout.SOUTH, controlPanel ) ;
    frame.add( mainPanel ) ;
    frame.setVisible( true ) ;
    frame.setResizable(false);
    frame.pack() ;
}
public class Listener implements ActionListener {
    public void actionPerformed( ActionEvent e ) {

    }
}
public String readFile() {
    StringBuilder sb = new StringBuilder();
    try {
        String inputLine;
        Scanner inFile = new Scanner (new File ("baby-names.txt"));
        int i = 0;
        int num = inFile.nextInt();
        nameList = new NameRecord[num];
        while ( inFile.hasNext() ) {
            inputLine = inFile.nextLine();
            System.out.println(nameList);        
            nameList[i] = new NameRecord(inputLine);
            displayArea.append(nameList[i] +"n");
            i++ ;
        }
    } catch(IOException io) {
        System.out.println(io) ;
    }
     return sb.toString();
}  // readFile()

}

这是我的名字记录:

import java.util.Scanner;
/**
A class to represent the data for one name over the 
decades.
KEEP THIS IN A SEPARATE FILE!
*/
public class NameRecord {
private String name ;
private int[] rank ;
public static final int START = 1900 ;
public static final int DECADES = 11 ;
/**
 * 
 * @param record
 */
public NameRecord(String record){
    //use a Scanner to get the data from the record
    Scanner line = new Scanner (record);
    name = line.next();
    rank = new int[DECADES] ;
    for(int i=0; i<DECADES; i++)
        rank[i] = line.nextInt();
}
public String getName() {
    return name ;
}
public void setName(String newName) {
    name = newName;
}
public int getRank(int d) {
    int decadeRank = rank[d];
    return decadeRank;
}
/** returns the best decade
*
* @return the best decade
*/  
public int bestDecade() {
    int best = rank[0];
    for(int i=1; i<DECADES; i++)
        if(rank[i] > best)
            best = rank[i];
    return best;
}
/** toString method for NameRecord
*
* @return student's name and rank
*/  
public String toString() {
    String result = getName() ;
    for(int i=0; i<DECADES; i++)
        result = result + " " + rank[i] ;
    return result ;
}
}

我建议您从readFile方法输出一个String数组,并从main中调用它。

String [] storage = readFile(fileName);

for(int i=0; i<storage.length; i++){
    displayArea.append(storage[i] + "n");
}

如果希望每个元素都在单独的行上,则添加是可选的。

或者,如果你只想在readFile方法中完成,

 while ( inFile.hasNext() ) {
        inputLine = inFile.nextLine();
        System.out.println(inputLine);       
        nameList[i] = new NameRecord(inputLine);
        displayArea.append(nameList[i] +"n");
        i++ ;
    }

由于我不知道你在哪里使用数组来设置文本,我只推荐这个

while ( inFile.hasNext() ) {
        inputLine = inFile.nextLine();
        System.out.println(inputLine);       
        nameList[i] = new NameRecord(inputLine);
        displayArea.append(nameList[i] + "n");
        i++ ;
}

我刚刚添加了一个append语句,它将附加到文本区域。

还要记住,您应该覆盖NameRecord中的toString()方法,以便获得所需的字符串输出

您不需要将参数fileName传递给该方法,因为您已经在该方法中使用了文字。

另一个建议是,让该方法返回一个字符串

 String readFile() {
        StringBuilder sb = new StringBuilder();
        try {
            String inputLine;
            Scanner inFile = new Scanner (new File ("baby-names.txt"));
            int i = 0;
            int num = inFile.nextInt();
            nameList = new NameRecord[num];
            while ( inFile.hasNext() ) {
                inputLine = inFile.nextLine();
                System.out.println(inputLine);       
                nameList[i] = new NameRecord(inputLine);
                sb.append(nameList[i]);
                i++ ;
        }
    } catch(IOException io) {
        System.out.println(io) ;
    }
    return sb.toString()'
}

然后在你的构造函数中

displayArea.setText(readFile());

编辑:要获得所需结果请尝试此

String readFile() {
        StringBuilder sb = new StringBuilder();
        sb.append("FIND RESULTS FOR Trinitynn");
        sb.append("DecadetRankn");
        sb.append("------t-----n");
        try {
            String inputLine;
            Scanner inFile = new Scanner (new File ("baby-names.txt"));
            int i = 0;
            int num = inFile.nextInt();
            nameList = new NameRecord[num];
            while ( inFile.hasNext() ) {
                inputLine = inFile.nextLine();
                System.out.println(inputLine);       
                nameList[i] = new NameRecord(inputLine);
                sb.append(nameList[i].getDecade() + "t" + nameList[i].getRank() + "n");
                i++ ;
        }
    } catch(IOException io) {
        System.out.println(io) ;
    }
    return sb.toString();
}

这是假设您的NameRecord类中有一个getDecade()getRank()

编辑:完整的可运行程序

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.Scanner;
public class NameViewer {
    JTextField nameTF;
    JTextArea displayArea;
    NameRecord[] namesArray;

    public static void main(String[] arg) {
        NameViewer app = new NameViewer();
    }
    public NameViewer() {
        JFrame frame = new JFrame("Name Surfer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        displayArea = new JTextArea(25, 50);
        displayArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(displayArea);
        mainPanel.add(BorderLayout.CENTER, scrollPane);
        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new GridLayout(1, 3));
        nameTF = new JTextField(7);
        controlPanel.add(nameTF);
        JButton find = new JButton(" Find ");
        controlPanel.add(find);
        find.addActionListener(new Listener());
        JButton match = new JButton(" Match ");
        controlPanel.add(match);
        match.addActionListener(new Listener());
        mainPanel.add(BorderLayout.SOUTH, controlPanel);
        read("names.txt");
        frame.add(mainPanel);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.pack();
    }
    public class Listener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
        }
    }
    private void read(String filename) {
        StringBuilder sb = new StringBuilder();
        try {
            String inputLine;
            Scanner inFile = new Scanner(new File(filename));
            int i = 0;
            int num = Integer.parseInt(inFile.nextLine().trim());
            namesArray = new NameRecord[num];
            String inputString;
            while (inFile.hasNextLine()) {
                inputString = inFile.nextLine();
                namesArray[i] = new NameRecord(inputString);
                displayArea.append(namesArray[i].toString() + "n");
            }
        } catch (IOException io) {
            System.out.println(io);
        }
    }  // readFile()
}
public class NameRecord {
    private String name;
    private final static int NUM_OF_DECADES = 11;
    private int[] ranks;
    public NameRecord(String inputString) {
        String[] split = inputString.split("\s+");
        this.name = split[0];
        ranks = new int[NUM_OF_DECADES];
        for (int i = 1; i < NUM_OF_DECADES; i++) {
            ranks[i - 1] = Integer.parseInt(split[i]);
        }
    }
    public String getName() {
        return name;
    }
    public void setName(String newName) {
        name = newName;
    }
    public int getHighRank(int d) {
        int decadeRank = ranks[d];
        return decadeRank;
    }
    public int[] getRank(){
        return ranks;
    }
    public int bestDecade() {
        int best = ranks[0];
        for (int i = 0; i < NUM_OF_DECADES; i++) {
            if (ranks[i] > best) {
                best = ranks[i];
            }
        }
        return best;
    }

    @Override
    public String toString() {
        String result = getName();
        for (int i = 0; i < NUM_OF_DECADES; i++) {
            result = result + " " + ranks[i];
        }
        return result;
    }
}

最新更新