Java on read from csv and display on jTable - java

I'm having stuck at reading back from csv wheres i'm success at creating the csv.
the problem I'm facing is I cant get a clue on how to obtain the values getting from csv back to the jTable.
I'm not having any other problems aside from public void fromCsv
class FCMS extends JFrame{
String header[] = {"Firstname","Lastname","FCMS ID","Email"};
String data[][];
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
JPanel pane = new JPanel();
JPanel pane_input = new JPanel();
JLabel lbl_firstname = new JLabel(" Firstname");
JLabel lbl_lastname = new JLabel(" Lastname");
JLabel lbl_id = new JLabel(" FCMS ID");
JLabel lbl_email = new JLabel(" Email");
JTextField txt_firstname = new JTextField(10);
JTextField txt_lastname = new JTextField(10);
JTextField txt_id = new JTextField(10);
JTextField txt_email = new JTextField(10);
JButton btn_add = new JButton("Add Entry");
JButton btn_Csv = new JButton("Export to Csv");
JButton btn_load = new JButton("Load From Csv");
public FCMS(){
setSize(200,200);
setPreferredSize(new Dimension(350,300));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
setTitle("Flight Crew Management System");
btn_add.setMnemonic(KeyEvent.VK_A);
btn_Csv.setMnemonic(KeyEvent.VK_E);
btn_load.setMnemonic(KeyEvent.VK_L);
pane_input.setLayout(new GridLayout(0,2));
pane_input.add(lbl_firstname);
pane_input.add(txt_firstname);
pane_input.add(lbl_lastname);
pane_input.add(txt_lastname);
pane_input.add(lbl_id);
pane_input.add(txt_id);
pane_input.add(lbl_email);
pane_input.add(txt_email);
pane_input.add(btn_add);
pane_input.add(btn_Csv);
pane_input.add(btn_load);
pane.setLayout(new BorderLayout());
pane.add(pane_input, BorderLayout.NORTH);
pane.add(new JScrollPane(table), BorderLayout.CENTER);
add(pane);
pack();
setVisible(true);
btn_add.addActionListener(new AksyonListener());
btn_Csv.addActionListener(new AksyonListener());
btn_load.addActionListener(new AksyonListener());
txt_email.addActionListener(new AksyonListener());
}
public void toCsv(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter Csv = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
Csv.write(model.getColumnName(i) + ",");
}
Csv.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
Csv.write(model.getValueAt(i,j).toString()+",");
}
Csv.write("\n");
}
Csv.close();
}catch(IOException e){ System.out.println(e); }
}
public void fromCsv(File file){
BufferedReader fileReader = null;
model.setRowCount(0);
try{
//Create the file reader
fileReader = new BufferedReader(new FileReader(file));
//Read the CSV file header to skip it
fileReader.readLine();
int fn = 0;
int ln = 1;
int id = 2;
int email = 3;
String line="";
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
// if (tokens.length > 0) {
// }
}
/* for(int i=0; i< tokens.length; i++) {
for(int j=0; j < tokens.length; j++) {
//Csv.read(model.getValueAt(i,j).toString()+"\t");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
}
// Csv.read("\n");
}*/
fileReader.close();
}catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
}
}
public static void main(String[] args){
new FCMS();
}
class AksyonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == btn_add || e.getSource() == txt_email){
String fn = txt_firstname.getText();
String ln = txt_lastname.getText();
String id = txt_id.getText();
String mail = txt_email.getText();
txt_firstname.setText("");
txt_lastname.setText("");
txt_id.setText("");
txt_email.setText("");
txt_firstname.requestFocus();
model.insertRow(model.getRowCount(), new Object[]{fn, ln, id, mail});
}
else if(e.getSource() == btn_Csv){
JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(FCMS.this);
if(option == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if(len > 4){
ext = filename.substring(len-4, len);
}
if(ext.equals(".csv")){
file = path + "\\" + filename;
}else{
file = path + "\\" + filename + ".csv";
}
toCsv(table, new File(file));
}
}
else if(e.getSource() == btn_load){
JFileChooser fc = new JFileChooser();
int option = fc.showOpenDialog(FCMS.this);
if(option == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if(len > 4){
ext = filename.substring(len-4, len);
}
if(ext.equals(".csv")){
file = path + "\\" + filename;
}else{
file = path + "\\" + filename + ".csv";
}
fromCsv(new File(file));
}
}
}
}
}
Problem is solved:
try{
//Create the file reader
fileReader = new BufferedReader(new FileReader(file));
//Read the CSV file header to skip it
fileReader.readLine();
int fn = 0;
int ln = 1;
int id = 2;
int email = 3;
String line="";
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
// if (tokens.length > 0) {
// }
}
/* for(int i=0; i< tokens.length; i++) {
for(int j=0; j < tokens.length; j++) {
//Csv.read(model.getValueAt(i,j).toString()+"\t");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
}
// Csv.read("\n");
}*/
fileReader.close();
}

String[] tokens = line.split(",");
Above is where you split one line of data into an array, so above is where you then need to take the data from the array and add it to the TableModel.
So your code should be:
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
Then there is no need for the second loop.
However, the above code will just append data to the existing "model", so you may also need to clear all the data in the model. You can do this by adding:
model.setRowCount(0);
before the loop.

Related

How to display Object array in JTable?

This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}

Problems with default table model

I am creating java editable table, and faced to problem: it "crashes" after reading data. Here is my table:
table.getTableHeader().setReorderingAllowed(false);
tableModel = new DefaultTableModel(new Object[]
{"#","1","2","3","4","5","6","7"},8);
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);
Reading from txt:
OK4.addActionListener(new ActionListener(){
#Override
File f = new File(fileName);
if(f.exists()){
try {
tableModel = new DefaultTableModel(new Object[]{"#","1","2","3","4","5","6","7"},0);
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String[] colHeaders = line.split("\\s+");
tableModel.setColumnIdentifiers(colHeaders);
while ((line = br.readLine()) != null) {
String[] data = line.split("\\s+");
tableModel.addRow(data);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}else{
JOptionPane.showMessageDialog(null, "this day is not saved");
};
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);
});
And main problems causing my sum field:
OK3.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int sum=0;
int number;
Object smth;
String Smth;
int kint2 = table.getRowCount()-1;
if(table.getValueAt(kint2, 1)=="total:"){
}else{
tableModel.addRow(new Object[]{});
int a = table.getRowCount()-1;
table.setValueAt("total:", a, 1);
}
for (int j = 2; j < 8; j++) {
for (int i = 0; i < table.getRowCount()-1; i++) {
smth = table.getValueAt(i,j);
Smth = (String) smth;
if (smth==null){
number=0;
}else{
number=Integer.parseInt(Smth);
}
sum=sum+number;
}
table.setValueAt(sum, table.getRowCount()-1, j);
sum=0;
}
}
});
Application stops calculate sum after being read from txt or calculates only first 4 rows sum. Have it something to do with my tableModel?
Thank you for answers.
The problem is that you add new rows with tablemodel and count rows with table. As discussed at "jTable row count VS model row count" your table won't update the rows count so always use tablemodel.getRowCount()

Can I set array in class from inside action listener? JAVA

Basically all I need to do is get array1 and array2 from each of my buttonlisteners and I have no clue how to do this as it is.. Right now the TextMatch button doesn't work because array1 and array2 are empty, is there a way to set them from the buttonlistener classes?
All I need is a way to set array1 and array2 as ss and sstwo so I can implement my TextTools.match() method
MAIN PROGRAM:
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab11 extends JPanel
{
private SuperString [] array1, array2;
private StringBuilder string, string2, string3, string4; //loads SuperStrings faster by appending all at once
private JRadioButton occurrence, alphabetical;
private JPanel text;
private JComboBox<Integer> input;
private JLabel label, file1,file2, unique, unique2,textmatch;
private JButton load, go,go2, TextMatch;
private CountLinkedList<SuperString> words, words3; //Change impliments CountList to extends BinaryCountTree
private OrderedLinkedList<SuperString> words2, words4;//Change impliments CountList to extends BinaryCountTree
private String filename,filename2;
private int width = 450;
private int height = 550;
private TextArea textarea,textarea2;
Scanner scan;
public Lab11()
{
TextListener textlistener = new TextListener();
ButtonListener listener = new ButtonListener();
Button2Listener listener2 = new Button2Listener();
Integer [] select = {1,2,3,4};
input = new JComboBox<Integer>(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File 1: ");
go2 = new JButton("Select Text File 2: ");
TextMatch = new JButton("TextMatch");
textmatch = new JLabel("");
label = new JLabel("N: " );
unique = new JLabel("");
unique2 = new JLabel("");
file1 = new JLabel("");
file1.setFont(new Font("Helvetica",Font.PLAIN,24));
unique.setFont(new Font("Helvetica",Font.PLAIN,24));
file2 = new JLabel("");
file2.setFont(new Font("Helvetica",Font.PLAIN,24));
unique2.setFont(new Font("Helvetica",Font.PLAIN,24));
occurrence= new JRadioButton("Occurrence");
occurrence.setMnemonic(KeyEvent.VK_O);
occurrence.addActionListener(listener);
occurrence.addActionListener(listener2);
occurrence.setSelected(true);
alphabetical = new JRadioButton("Alphabetical");
alphabetical.setMnemonic(KeyEvent.VK_A);
alphabetical.addActionListener(listener);
alphabetical.addActionListener(listener2);
ButtonGroup group = new ButtonGroup();
group.add(occurrence);
group.add(alphabetical);
go.addActionListener(listener);
go2.addActionListener(listener2);
input.addActionListener(listener);
input.addActionListener(listener2);
TextMatch.addActionListener(textlistener);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(1000,700));
text.add(textarea);
text.add(textarea2);
add(occurrence);
add(alphabetical);
add(label);
add(input);
add(go);
add(file1);
add(unique);
add(go2);
add(file2);
add(unique2);
add(TextMatch);
add(textmatch);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
string = new StringBuilder();
string2 = new StringBuilder();
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text1= file.getName();
file1.setText(text1);
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
words2 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words.add(ss );
words2.add(ss2 );
}
}
SuperString[] array1 = new SuperString[words.size()];
SuperString[] ss = new SuperString[words.size()];
SuperString[] ss2 = new SuperString[words2.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word: words)
{
ss[i] = word;
array1[i] = word;
i++;
}
int j=0;
for(SuperString word: words2)
{
ss2[j] = word;
j++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
count++;
string.append(Integer.toString(count)+ " "+ word+ "\n");
}
if(occurrence.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string.toString());
string.replace(0,string.length()*2, "");
}
for(SuperString word : ss2)
{
count2++;
string2.append(Integer.toString(count2)+ " "+ word.toString()+ "\n");
}
if(alphabetical.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string2.toString());
string2.replace(0,string2.length()*2, "");
}
unique.setText("Unique Count: "+ Integer.toString(words.size()));
}
}
public class Button2Listener implements ActionListener
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
string3 = new StringBuilder();
string4 = new StringBuilder();
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text2= file.getName();
file2.setText(text2);
filename2 = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words3 = new CountLinkedList<SuperString>();
words4 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words3.add(ss );
words4.add(ss2 );
}
textarea2.setText("");
}
SuperString[] array2 = new SuperString[words3.size()];
SuperString[] sstwo = new SuperString[words3.size()];
SuperString[] ss2two = new SuperString[words4.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word2: words3)
{
sstwo[i] = word2;
array2[i] = word2;
i++;
}
int j=0;
for(SuperString word2: words4)
{
ss2two[j] = word2;
j++;
}
Arrays.sort(sstwo, new SuperStringCountOrder());
for(SuperString word2 : sstwo)
{
count++;
string3.append(Integer.toString(count)+ " "+ word2+ "\n");
}
if(occurrence.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string3.toString());
}
for(SuperString word2 : ss2two)
{
count2++;
string4.append(count2+" "+ " "+word2+"\n");
}
if(alphabetical.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string4.toString());
}
unique2.setText("Unique Count: "+ Integer.toString(words3.size()));
}
}
public class TextListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() ==TextMatch)
{
textmatch.setText("The match is: "+ TextTools.match(array1,array2));
}
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 11");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Lab11());
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
TEXT MATCH PROGRAM:
import java.util.Arrays;
public class TextTools
{
public static double match(SuperString[] X, SuperString[] Y)
{
double length1 = 0, length2 = 0;
Arrays.sort(X);
Arrays.sort(Y);
for(SuperString token : X)
{
double value = token.count();
length1 += value*value;
}
length1 = Math.sqrt(length1);
for(SuperString token : Y)
{
double value = token.count();
length2 += value*value;
}
length2 = Math.sqrt(length2);
double total = 0;
int j=0;
for(int i=0;i<X.length;i++)
{
while(j < Y.length && X[i].compareTo(Y[j])>0 )
j++;
if(j == Y.length)
return total/(length1*length2);
if(X[i].compareTo(Y[j]) == 0)
total += X[i].count()*Y[j].count();
}
return total/(length1*length2);
}
}
Turns out I'm erasing over my array1 and array2 by re declaring SuperString in the actionlistener

Getting Null Pointed exception error but runs fine? Java JComboBox (DropDown box)

So Integer N here is controlled by a JComboBox basically a drop down menu 1-4. My problem is that I get a nullpointerexception error when I initially set N from the box..any ideas how to fix this? I tested it by printing out what N was in both actionlistener instances and it's null in the first one and it's correct in the second one.
import java.awt.GridLayout;
import javax.swing.JFrame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import javax.swing.JComboBox;
public class Lab10 extends JPanel
{
private StringBuilder string, string2, string3, string4; //loads SuperStrings faster by appending all at once
private JRadioButton occurrence, alphabetical;
private JPanel text;
private JComboBox<Integer> input;
private JLabel label, file1,file2, unique, unique2;
private JButton load, go,go2;
private CountLinkedList<SuperString> words, words3; //Change impliments CountList to extends BinaryCountTree
private OrderedLinkedList<SuperString> words2, words4;//Change impliments CountList to extends BinaryCountTree
private String filename,filename2;
private int width = 450;
private int height = 550;
private TextArea textarea,textarea2;
Scanner scan;
public Lab10()
{
string = new StringBuilder();
string2 = new StringBuilder();
string3 = new StringBuilder();
string4 = new StringBuilder();
ButtonListener listener = new ButtonListener();
Button2Listener listener2 = new Button2Listener();
Integer [] select = {1,2,3,4};
input = new JComboBox<Integer>(select);
text = new JPanel(new GridLayout(1,2));
go = new JButton("Select Text File 1: ");
go2 = new JButton("Select Text File 2: ");
label = new JLabel("N: " );
unique = new JLabel("");
unique2 = new JLabel("");
file1 = new JLabel("");
file1.setFont(new Font("Helvetica",Font.PLAIN,24));
unique.setFont(new Font("Helvetica",Font.PLAIN,24));
file2 = new JLabel("");
file2.setFont(new Font("Helvetica",Font.PLAIN,24));
unique2.setFont(new Font("Helvetica",Font.PLAIN,24));
occurrence= new JRadioButton("Occurrence");
occurrence.setMnemonic(KeyEvent.VK_O);
occurrence.addActionListener(listener);
occurrence.addActionListener(listener2);
occurrence.setSelected(true);
alphabetical = new JRadioButton("Alphabetical");
alphabetical.setMnemonic(KeyEvent.VK_A);
alphabetical.addActionListener(listener);
alphabetical.addActionListener(listener2);
ButtonGroup group = new ButtonGroup();
group.add(occurrence);
group.add(alphabetical);
go.addActionListener(listener);
go2.addActionListener(listener2);
input.addActionListener(listener);
input.addActionListener(listener2);
textarea = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea2 = new TextArea("",0,0,TextArea.SCROLLBARS_VERTICAL_ONLY);
textarea.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea2.setFont(new Font("Helvetica",Font.PLAIN,24));
textarea.setPreferredSize(new Dimension(width,height));
textarea2.setPreferredSize(new Dimension(width,height));
setPreferredSize(new Dimension(1000,700));
text.add(textarea);
text.add(textarea2);
add(occurrence);
add(alphabetical);
add(label);
add(input);
add(go);
add(file1);
add(unique);
add(go2);
add(file2);
add(unique2);
add(text);
textarea.setText("No File Selected");
textarea2.setText("No File Selected");
}
public class ButtonListener implements ActionListener //makes buttons do things
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text1= file.getName();
file1.setText(text1);
filename = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words = new CountLinkedList<SuperString>();
words2 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words.add(ss );
words2.add(ss2 );
}
textarea.setText("");
}
SuperString[] ss = new SuperString[words.size()];
SuperString[] ss2 = new SuperString[words2.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word: words)
{
ss[i] = word;
i++;
}
int j=0;
for(SuperString word: words2)
{
ss2[j] = word;
j++;
}
Arrays.sort(ss, new SuperStringCountOrder());
for(SuperString word : ss)
{
count++;
string.append(Integer.toString(count)+ " "+ word+ "\n");
}
if(occurrence.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string.toString());
}
for(SuperString word : ss2)
{
count2++;
string2.append(Integer.toString(count2)+ " "+ word.toString()+ "\n");
}
if(alphabetical.isSelected())
{
textarea.setText("");
textarea.append(" "+filename+" has wordcount: "+words.size()+
"\n-------------------------\n\n");
textarea.append(string2.toString());
}
unique.setText("Unique Count: "+ Integer.toString(words.size()));
}
}
public class Button2Listener implements ActionListener
{
JFileChooser chooser = new JFileChooser("../Text");
public void actionPerformed(ActionEvent event)
{
Integer N = input.getSelectedIndex()+1;
if(event.getSource() == go2)
{
int returnvalue = chooser.showOpenDialog(null);
if(returnvalue == JFileChooser.APPROVE_OPTION)
{
try
{
File file = chooser.getSelectedFile();
String text2= file.getName();
file2.setText(text2);
filename2 = file.getName();
System.err.println(filename);
scan = new Scanner(file);
}
catch (IOException e)
{
System.err.println("IO EXCEPTION");
return;
}
}
else
{
return;
}
String[] storage = new String[N];
words3 = new CountLinkedList<SuperString>();
words4 = new OrderedLinkedList<SuperString>();
for(int i=1;i<N;i++)
storage[i] = scan.next().toLowerCase().replace(",","").replace(".","");
while(scan.hasNext())
{
for(int i=0;i<=N-2;i++)
storage[i] = storage[i+1];
storage[N-1] = scan.next().toLowerCase();
storage[N-1] = storage[N-1].replace(",","").replace(".","").replaceAll("[^A-Za-z0-9]", "")
.replaceAll("[.,':]","");
SuperString ss = new SuperString(storage);
SuperString ss2= new SuperString(storage);
words3.add(ss );
words4.add(ss2 );
}
textarea2.setText("");
}
SuperString[] sstwo = new SuperString[words3.size()];
SuperString[] ss2two = new SuperString[words4.size()];
int i=0;
int count =0, count2= 0;
for(SuperString word2: words3)
{
sstwo[i] = word2;
i++;
}
int j=0;
for(SuperString word2: words4)
{
ss2two[j] = word2;
j++;
}
Arrays.sort(sstwo, new SuperStringCountOrder());
for(SuperString word2 : sstwo)
{
count++;
string3.append(Integer.toString(count)+ " "+ word2+ "\n");
}
if(occurrence.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string3.toString());
}
for(SuperString word2 : ss2two)
{
count2++;
string4.append(count2+" "+ " "+word2+"\n");
}
if(alphabetical.isSelected())
{
textarea2.setText("");
textarea2.append(" "+filename2+" has wordcount: "+words3.size()+
"\n-------------------------\n\n");
textarea2.append(string4.toString());
}
unique2.setText("Unique Count: "+ Integer.toString(words3.size()));
}
}
public static void main(String[] arg)
{
JFrame frame = new JFrame("Lab 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Lab10());
frame.pack();
frame.setVisible(true);
}
}
Your question doesn't make sense as written:
Integer N = input.getSelectedIndex()+1;
System.out.println(N);
The println cannot possibly tell you that N is null.
If the expression on the RHS of the = executes without an exception, then N is guaranteed to be non-null. The getSelectedIndex() call returns an int, and the result of the addition will be an int. That will then be autoboxed to an Integer, and autoboxing can NEVER give you a null.
If the expression on the RHS of the = throws an exception, then the println statement won't be executed.
In other words, what you are describing is Impossible.
So what I think is actually happening is one of the following:
Your code is throwing a NullPointerException in the first statement because input is null, and you have misdiagnosed that as meaning that N is null.
This code is sufficiently different from your actual code that it is not possible to understand what is really going on.
You have made a mistake in the compiling / running / deploying of your code, such that you are running a stale binary.
Your code isn't compilable the way it is now. You can't have multiple public classes in the same file. Also, to access the selected index from a JComboBox, this is what your actionPerformed method should look like.
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
int n = cb.getSelectedIndex();
//etc
}

Java Serialization issues

I have this code that writes an object:
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
And this code that loads the object:
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
I'm pretty sure that saving works, as when I opened the file in notepad++ I saw most of the data that I had saved, but when I load there is no data in module list.
Full source code:
import java.io.*;
import java.util.*;
public class Model implements java.io.Serializable {
private Student[] studentList = new Student[0];
private Module[] moduleList = new Module[0];
public void menu() {
while (true) {
System.out.println ("MENU");
System.out.println ("");
System.out.println (" 1 - Run Tests");
System.out.println (" 2 - Add Student");
System.out.println (" 3 - Add Module");
System.out.println (" 4 - Add Student To Module");
System.out.println (" 5 - Save System (Text file)");
System.out.println (" 6 - Load System (Text file)");
System.out.println (" 7 - Save System (Serialized)");
System.out.println (" 8 - Load System (Serialized)");
System.out.println (" 9 - Print Report");
System.out.println ("");
System.out.print ("Enter choice: ");
String input = keyboard.readString();
switch (input) {
case "1" :
runTests();
break;
case "2" :
System.out.print("First Name : ");
String fN = keyboard.readString();
System.out.print("Surname : ");
String sN = keyboard.readString();
System.out.print("Course Code : ");
String c = keyboard.readString();
System.out.print("User ID : ");
String iD = keyboard.readString();
AddStudent(iD, sN, fN, c);
break;
case "3" :
System.out.print("Module Code : ");
String code = keyboard.readString();
String[] temp = new String[0];
AddModule(code,temp);
break;
case "4" :
System.out.print("Module Code : ");
code = keyboard.readString();
Module m = findAModule(code);
if (m != null) {
System.out.print("User ID : ");
iD = keyboard.readString();
Student s = findAStudent(iD);
if (s != null) {
m.addThisStudent(s);
} else {
System.out.println("Student not found");
}
} else {
System.out.println("Module not found");
}
break;
case "5" :
saveToTextFiles();
break;
case "6" :
loadFromTextFiles();
break;
case "7" :
saveSerialized();
break;
case "8" :
break;
case "9" :
printReport();
break;
}
}
}
public void runTests() {
loadFromTextFiles();
saveSerialized();
printReport();
}
public void loadFromTextFiles() {
studentList = new Student[0];
moduleList = new Module[0];
try {
Scanner fileReader = new Scanner(new InputStreamReader(new FileInputStream("students.txt")));
int num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String u = fileReader.nextLine();
String sn = fileReader.nextLine();
String fn = fileReader.nextLine();
String c = fileReader.nextLine();
AddStudent(u, sn, fn, c);
}
fileReader.close();
fileReader = new Scanner(new InputStreamReader(new FileInputStream("modules.txt")));
num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String code = fileReader.nextLine();
int numOfStudents = fileReader.nextInt(); fileReader.nextLine();
String[] students = new String[numOfStudents];
for (int j = 0; j < numOfStudents; j++) {
students[j] = fileReader.nextLine();
}
AddModule(code, students);
}
fileReader.close();
} catch (IOException e) {}
}
public void saveToTextFiles () {
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("students.txt")));
outfile.println(studentList.length);
for (int i = 0; i < studentList.length; i++) {
outfile.println(studentList[i].getUID());
outfile.println(studentList[i].getSN());
outfile.println(studentList[i].getFN());
outfile.println(studentList[i].getDegree());
}
outfile.close();
outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("modules.txt")));
outfile.println(moduleList.length);
for (int i = 0; i < moduleList.length; i++) {
outfile.println(moduleList[i].getCode());
outfile.println(moduleList[i].getStudents().length);
for (int j = 0; j < moduleList[i].getStudents().length; j++) {
outfile.println(moduleList[i].getStudents()[j]);
}
}
outfile.close();
} catch (IOException e) {}
}
public void saveSerialized() {
try {
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
FileOutputStream fileOut2 = new FileOutputStream("Module.ser");
ObjectOutputStream out2 = new ObjectOutputStream(fileOut2);
out2.writeObject(studentList);
out2.close();
fileOut2.close();
FileOutputStream fileOut3 = new FileOutputStream("Student.ser");
ObjectOutputStream out3 = new ObjectOutputStream(fileOut3);
out3.writeObject(moduleList);
out3.close();
fileOut3.close();
} catch (IOException e) {}
}
public void loadSerialized() {
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
}
private Module[] getModuleList() {
return moduleList;
}
private Student[] getStudentList() {
return studentList;
}
private void setModuleList(Module[] m) {
moduleList = m.clone();
}
private void setStudentList(Student[] s) {
studentList = s.clone();
}
private void AddModule(String code, String[] students) {
int length = moduleList.length;
Module NewArray[] = new Module[length + 1];
for (int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Module(moduleList[i]);
}
}
NewArray[length] = new Module(code, students);
moduleList = NewArray.clone();
}
private void AddStudent(String u, String sn, String fn, String c) {
int length = studentList.length;
Student NewArray[] = new Student[length + 1];
for(int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Student(studentList[i]);
}
}
NewArray[length] = new Student(u, sn, fn, c);
studentList = NewArray.clone();
}
public void printReport() {
for (int i = 0; i < moduleList.length; i++) {
System.out.println(moduleList[i].toString(this));
}
}
public Student findAStudent(String uid) {
for (int i = 0; i < studentList.length; i++) {
if (studentList[i].getUID().compareTo(uid) == 0) {
return studentList[i];
}
}
return null;
}
public Module findAModule(String code) {
for (int i = 0; i < moduleList.length; i++) {
if (moduleList[i].getCode().compareTo(code) == 0) {
return moduleList[i];
}
}
return null;
}
}
Look at your code sample, in particular the switch statement:
switch (input) {
...
case "8" :
break;
...
}
I'd assume the method loadSerialized should be called there but it's missing and is not called anywhere else in the code.
Once you actually call the method that does the loading, the code will work, assuming you have declared a serialVersionUID for both Student and Module.
Edit: why using serialization to persist objects is a bad idea
In simple terms, using serialization to persist objects is brittle.
An object's serialized form is tied to its class. Classes tend to change over time, meaning the serialized instance of the old cannot be loaded into the new.
While you can work round this by setting a serialVersionUID doing so introduces a reverse of the problem where, in the case new fields are introduced, the new cannot be read into objects of the old class, which can be a problem if you do rolling updates to the deployed system.
There's a host of other reasons - it's not easily readable (meaning you can't update it like you would a database or XML/JSON doc), it's inefficient, etc.

Categories