1

The following code should read a list of students and their grades from a file, compare them to each other then display the student with the highest average

public class CSDept implements Comparable{
private String studentName;
private double java;
private double dataStructure;
private double algorithms;
private int numStudents;


public CSDept(){

}

public CSDept(String studentName,double java,double dataStructure,double algorithms){
    this.studentName=studentName;
    this.java=java;
    this.dataStructure=dataStructure;
    this.algorithms=algorithms;
}

public String getStudentName() {
    return studentName;
}

public void setStudentName(String studentName) {
    this.studentName = studentName;
}

public String getJava() {
    return java+" ";
}

public void setJava(double java) {
    this.java = java;
}

public String getDataStructure() {
    return dataStructure+" ";
}

public void setDataStructure(double dataStructure) {
    this.dataStructure = dataStructure;
}

public String getAlgorithms() {
    return algorithms+" ";
}

public void setAlgorithms(double algorithms) {
    this.algorithms = algorithms;
}


public int getNumStudents() {
    return numStudents;
}

public double getAvg(){
    return (java+algorithms+dataStructure)/3;
}



public int compareTo(Object student) {
    if(this.getAvg()>((CSDept)student).getAvg()) return 1;
    if (this.getAvg()<((CSDept)student).getAvg()) return -1;
    return 0;
}

public String toString(){
    return studentName+":\n"+"\t"+"Java:  "+java+"\t"+"Data Structure :  "+dataStructure+"\t"+"Algorithms:  "+algorithms+"\n";
}}

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.util.*;

    import javax.swing.*;
    import javax.swing.border.TitledBorder;


public class CSDeptFrame extends JFrame{
private JPanel pnlInput=new JPanel(new GridLayout(4,2));
private JPanel pnlOutput=new JPanel(new BorderLayout());
private JPanel pnlFinal=new JPanel(new GridLayout(1,2));

private TitledBorder brdInput=new TitledBorder("Marks");
private TitledBorder brdOutput=new TitledBorder("First Student");

private JLabel lblName=new JLabel("Student Name");
private JLabel lblJava=new JLabel("Java");
private JLabel lblDataStructure=new JLabel("Data Structure");
private JLabel lblAlgorithm=new JLabel("Algorithm");
static JLabel lblFirst=new JLabel("The First Student is :");

static JTextField txtName=new JTextField(20);
static JTextField txtJava=new JTextField(20);
static JTextField txtDataStructure=new JTextField(20);
static JTextField txtAlgorithm=new JTextField(20);

static JButton btnFirst=new JButton("Who is The First Student?");

public CSDeptFrame(String title){
    super(title);
    pnlInput.setBorder(brdInput);
    pnlInput.add(lblName);
    pnlInput.add(txtName);
    pnlInput.add(lblJava);
    pnlInput.add(txtJava);
    pnlInput.add(lblDataStructure);
    pnlInput.add(txtDataStructure);
    pnlInput.add(lblAlgorithm);
    pnlInput.add(txtAlgorithm);

    pnlOutput.setBorder(brdOutput);
    pnlOutput.add(btnFirst,BorderLayout.NORTH);
    pnlOutput.add(lblFirst,BorderLayout.SOUTH);

    pnlFinal.add(pnlInput);
    pnlFinal.add(pnlOutput);

    setLayout(new BorderLayout());
    add(pnlFinal);}

public static void main(String[] args){
    CSDeptFrame frame=new CSDeptFrame("CS DEPT");
    frame.setSize(450,200);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    final ArrayList<CSDept> cS= new ArrayList();
    File readFile =new File("read.txt");
    final File writeFile=new File("write.txt");


    try {
        Scanner scan=new Scanner(readFile);
        while(scan.hasNext()){
            CSDept student=new CSDept();
            student.setStudentName(scan.next());
            student.setJava(scan.nextDouble());
            student.setDataStructure(scan.nextDouble());
            student.setAlgorithms(scan.nextDouble());
            cS.add(student);


        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "OPS! File is not found");
        }

    btnFirst.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            CSDept firstStudent=new CSDept();
            firstStudent.setStudentName(cS.get(0).getStudentName());
            firstStudent.setJava(Double.parseDouble(cS.get(0).getJava()));
            firstStudent.setDataStructure(Double.parseDouble(cS.get(0).getDataStructure()));
            firstStudent.setAlgorithms(Double.parseDouble(cS.get(0).getAlgorithms()));

            for (int i=0;i<cS.size();i++){
                if (cS.get(i).compareTo(cS.get(i+1))==-1){
                    firstStudent=cS.get(i+1);
                }
            }
            txtName.setText(firstStudent.getStudentName());
            txtJava.setText(firstStudent.getJava());
            txtDataStructure.setText(firstStudent.getDataStructure());
            txtAlgorithm.setText(firstStudent.getAlgorithms());
            lblFirst.setText("The First Student is: "+ txtName.getText());
            PrintWriter out;
            try {
                out = new PrintWriter(new BufferedWriter(new FileWriter(writeFile,true)));
                for (CSDept cs: cS){

                    out.println(cs.toString());
                    out.print("The first student is " + firstStudent.toString());
                }
                 out.close();
            } catch (IOException e1) {
                e1.printStackTrace();
                JOptionPane.showMessageDialog(null, "OPS! File in Not Found");
            }

        }
    });

}}

But the problem is that the following statements don't add any objects to the arraylist, what's the problem with it?

try {
        Scanner scan=new Scanner(readFile);
        while(scan.hasNext()){
            CSDept student=new CSDept();
            student.setStudentName(scan.next());
            student.setJava(scan.nextDouble());
            student.setDataStructure(scan.nextDouble());
            student.setAlgorithms(scan.nextDouble());
            cS.add(student);


        }
Raya Rateb
  • 65
  • 1
  • 8
  • 2
    The List `cS` is empty, so there is no element at index 0. – Chris Forrence Jan 05 '15 at 20:08
  • You could avoid this by using an iterator or enhanced `for` loop rather than `List#get(int index)` to traverse the list. – Luiggi Mendoza Jan 05 '15 at 20:09
  • 1
    cS.get(0) will result in an out of bounds. You have a list, but it is empty. –  Jan 05 '15 at 20:09
  • Why is it empty? These statements should be filling it : try { Scanner scan=new Scanner(readFile); while(scan.hasNext()){ CSDept student=new CSDept(); student.setStudentName(scan.next()); student.setJava(scan.nextDouble()); student.setDataStructure(scan.nextDouble()); student.setAlgorithms(scan.nextDouble()); cS.add(student); } – Raya Rateb Jan 05 '15 at 20:10
  • @RayaRateb Correct, that's the question you should be asking now. – Chris Forrence Jan 05 '15 at 20:11
  • 1
    check if your program enters this loop: while scan.hasNext() –  Jan 05 '15 at 20:11
  • 1
    @RayaRateb, check content of your file `read.txt` – pbespechnyi Jan 05 '15 at 20:12
  • @pbespechnyi I think the problem is not the content of the file but its location. OP: make sure the file is physically found by using `System.out.println("read.txt exists? " + readFile.exists());` – Luiggi Mendoza Jan 05 '15 at 20:19
  • But if the file doesn't exist it will throw an exception, am I right? – Raya Rateb Jan 05 '15 at 20:21
  • Then it means you're reading from the file you expect. – Luiggi Mendoza Jan 05 '15 at 20:23
  • Simply println the name of the student in the while loop. You may have an existing empty file in another folder, etc. Also, make sure the showMessageDialog works so you don't overlook a file-not-found. – laune Jan 05 '15 at 20:25
  • This is a great opportunity to learn how to use a debugger. – Luiggi Mendoza Jan 05 '15 at 20:27

1 Answers1

2

You problem is that you are trying to get an element at a specific index from an empty list:

final ArrayList<CSDept> cS= new ArrayList();

// ...

public void actionPerformed(ActionEvent e) {
    // ...
    firstStudent.setStudentName(cS.get(0).getStudentName()); // ArrayList cS is empty here
    // ...

Maybe you could add a check to make sure the list is not empty before accessing the elements:

public void actionPerformed(ActionEvent e) {
    if(!cS.isEmpty()) {
        // do stuff
    }

The reason your list is empty could be that you are reading an empty file "read.txt" so your while loop condition is never true

Scanner scan=new Scanner(readFile); // this text file is probably empty
while(scan.hasNext()){              // which makes this condition always false so loop is never executed
    CSDept student=new CSDept();
    student.setStudentName(scan.next());
    student.setJava(scan.nextDouble());
    student.setDataStructure(scan.nextDouble());
    student.setAlgorithms(scan.nextDouble());
    cS.add(student);
}

Furthermore, you have an ArrayIndexOutOfBoundsException risk in the for loop inside actionPerformed(). You compare current element with the next element which will, once i corresponds to the index of the last element, give an AIOBE in the comparison statement with element at index i + 1:

for (int i=0;i<cS.size();i++){
    if (cS.get(i).compareTo(cS.get(i+1))==-1){  // once i = cS.size() - 1, you will get an AIOBE here
        firstStudent=cS.get(i+1);
    }
}

You can fix this by starting the loop at i = 1 and comparing with element at i - 1 or use a forEach loop which is a cleaner way of achieving this since it doesn't involve indexed access.

Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99
  • My file isn't empty, is there anything wrong with the code itself? – Raya Rateb Jan 05 '15 at 20:16
  • When you are reading files, check every possible error: file not found, empty, bad format, ... After doing that, check the content of scanner and if the content is succesfully loaded –  Jan 05 '15 at 20:17
  • Did you put a breakpoint inside the `while` loop above and checked if the loop is ever entered? – nem035 Jan 05 '15 at 20:17