1

我在从一维向量“v”转换到二维向量“myVector”时遇到问题。如果您能帮我解决这个问题,将不胜感激。接受任何建议。

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class InsertDataFinal {

public static void main(String args[]) {
    Vector<String> v = new Vector<String>(3);

    Vector<Vector<String>> myVector = new Vector<Vector<String>>();
    int i = 0;
    int j = 0;
    try {

        FileReader fReader = new FileReader("Password.txt");
        BufferedReader inFile = new BufferedReader(fReader);
        String input;
        String[] temp;
        while ((input = inFile.readLine()) != null) {

            temp = input.split(" ");

            for (i = 0; i < temp.length; i++) {

                v.add(temp[i]);
            }

            myVector.add(j, v);
            j++;
        }

    } catch (Exception e) {
        System.out.println("ERROR");
    }

    Vector<String> columnNames = new Vector<String>(3);
    columnNames.addElement("Website");
    columnNames.addElement("Username");
    columnNames.addElement("Password");
    DefaultTableModel model = new DefaultTableModel(myVector, columnNames);
    JTable table = new JTable();
    table.setModel(model);
    JScrollPane scrollpane = new JScrollPane(table);
    JPanel panel = new JPanel();
    panel.add(scrollpane);
    JFrame frame = new JFrame();
    frame.add(panel, "Center");
    frame.pack();
    frame.setVisible(true);
    }
}
4

1 回答 1

2

您的示例继续扩展Vector<String>名为的单个实例v。相反,创建一个新实例并将其添加到myVector. 此外,限制变量的范围并捕获最具体的异常。

Vector<Vector<String>> myVector = new Vector<Vector<String>>();
try {
    FileReader fReader = new FileReader("temp.txt");
    BufferedReader inFile = new BufferedReader(fReader);
    String input;
    while ((input = inFile.readLine()) != null) {
        String[] temp = input.split(" ");
        Vector<String> v = new Vector<String>(3);
        for (int i = 0; i < temp.length; i++) {
            v.add(temp[i]);
        }
        myVector.add(v);
    }
} catch (IOException e) {
    e.printStackTrace(System.err);
}
于 2013-04-19T18:51:55.213 回答