Trouble getting input for object array

Matt

I am trying to create a class that receives data about a person's name, exam subject, and exam score. I have these classes so far:

APExam:

public class APExam {
   //instance variables
   private String mySubject;
   private int myScore;
   
   //constructors
   public APExam(String subject, int score) {
      mySubject = subject;
      myScore = score;
   }
   public APExam() {
      mySubject = "";
      myScore = 1;
   }
   
   //getters and setters
   public void setSubject(String s) {
      mySubject = s;
   }
   public String getSubject() {
      return mySubject;
   }
   public void setScore(int score) {
      myScore = score;
   }
   public int getScore() {
      return myScore;
   }
   
   //compareTo
   public String compareTo(int s) {
      if(myScore == s)
         return "Scores are equal.";
      else if(myScore > s)
         return "The first score is greater than the second score.";  
      else 
         return "The second score is greater than the first score.";
   }
   
   //equals
   public boolean equals(String str) {
      return mySubject.equals(str);
   }
   
   //toString
   public String toString() {
      return "Subject: " + mySubject + "\nScore: " + myScore;
   }
}

APStudent:

public class APStudent {
   //instance variables
   private String myFirstName;
   private String myLastName;
   private ArrayList<APExam> myExams = new ArrayList<APExam>();
   
   //constructors
   public APStudent(String fname, String lname) {
      myFirstName = fname;
      myLastName = lname;
   }
   public APStudent() {
      myFirstName = "";
      myLastName = "";
   }
   
   //getters and setters
   public void setFirstName(String fname) {
      myFirstName = fname;
   } 
   public String getFirstName() {
      return myFirstName;
   }
   public void setLastName(String lname) {
      myLastName = lname;
   }
   public String getLastName() {
      return myLastName;
   }
   public ArrayList<APExam> getExams() {
      return myExams;
   }
   
   //addExam
   public void addExam(APExam ex) {
      myExams.add(ex);
   }
   
   //computeExamAverage
   public double computeExamAverage(List<APExam> exams) {
      int sum = 0;
      for(int i = 0; i < exams.size(); i++) {
         sum += exams.get(i).getScore();
      }
      return (double) sum / exams.size();
   }
   
   //findHighestExamScore
   public int findHighestExamScore(List<APExam> exams) {
      int max = exams.get(0).getScore();
      for(APExam ex : exams) {
         if(ex.getScore() > max) {
            max = ex.getScore();
         }
      }
      return max;
   }
   
   //numberOfFives
   public int numberOfFives(List<APExam> exams) {
      int fiveCount = 0;
      for(APExam ex : exams) {
         if(ex.getScore() == 5) {
            fiveCount++;
         }
      }
      return fiveCount;
   }
}

ArrayListTest:

public class ArrayListTest {
   public static void main(String[] args) {
      //instance variables
      final String QUIT = "end";
      Scanner sc = new Scanner(System.in);
      ArrayList<APExam> myExams = new ArrayList<APExam>();
      APStudent student = new APStudent();
      String fname, lname, sub, input = "";
      int score;
      
      //prompt for info
      System.out.print("Enter first name: ");
      fname = sc.nextLine();
      student.setFirstName(fname);
      System.out.print("\nEnter last name: ");
      lname = sc.nextLine();
      student.setLastName(lname);
      while(!input.equals(QUIT)) {
         APExam ap = new APExam();
         System.out.print("\nEnter exam subject or 'end' to quit: ");
         input = sc.nextLine();
         sub = input;
         ap.setSubject(sub);
         System.out.print("\nEnter exam score: ");
         score = sc.nextInt();
         ap.setScore(score);
         student.addExam(ap);
         sc.nextLine();
         
      }
      
      //display information
      System.out.println(student.getExams());
      System.out.println("Name: " + student.getFirstName() + " " + student.getLastName());
      System.out.println("Exam average score: " + student.computeExamAverage(myExams));
      System.out.println("Highest score: " + student.findHighestExamScore(myExams));
      System.out.println("Number of fives: " + student.numberOfFives(myExams));
      
      System.out.println();
      
      
      for(int i = 0; i < myExams.size(); i++) {
         System.out.println(myExams.get(i));
      }
      
      //prompt for search
      System.out.println("1 sequential search" 
                        + "\n2 binary search"
                        + "\n3 exit");
      input = sc.nextLine();
      while(!((input.equals("1") || input.equals("2") || input.equals("3")))) {
         switch(input) {
            case "1":
               sequentialSearch(myExams, 3);
               break;
            case "2":
               binarySearch(myExams, 2);
               break;
            case "3":
               break;
         }
      }
   }
}

For some reason in the ArrayListTest class it doesn't create an APExam object with the inputted scores and subjects. Is there something wrong with the while loop? Or is something else wrong?

AP11

Your problem is that you are for some reason passing variable List<APExam> exams into your functions. When you are doing that you are passing a empty ArrayList<APExam> and that's why it throws a IndexOutOfBoundsException.

You shouldn't pass anything and just use the APStudent's myExams list.

public double computeExamAverage() {
    double sum = 0;
    for (APExam myExam : myExams) {
        sum += myExam.getScore();
    }
    return sum / myExams.size();
}

public int findHighestExamScore() {
    int max = 0;
    for(APExam exam : myExams) {
        if(exam.getScore() > max) max = exam.getScore();
    }
    return max;
}

public int numberOfFives() {
    return (int) myExams.stream().filter(apExam -> apExam.getScore() == 5).count();
}

EDIT: I would like to comment on your main method too. You should use the parametrized constructors instead of default one and setters. And you should check on the input being "end" before you ask for grade.

public static void main(String[] args) {
    final String QUIT = "end"; // not really necessary, but ok
    Scanner sc = new Scanner(System.in);
    String firstName, lastName, subject;
    int score;

    //prompt for info
    System.out.print("Enter first name: ");
    firstName = sc.nextLine();
    System.out.print("\nEnter last name: ");
    lastName = sc.nextLine();
    APStudent student = new APStudent(firstName, lastName); // use of parametrized constructor
    while(true) {
        System.out.print("\nEnter exam subject or 'end' to quit: ");
        subject = sc.nextLine();
        if (subject.equals(QUIT)) break; // check if user wants to end it
        System.out.print("\nEnter exam score: ");
        score = sc.nextInt();
        student.addExam(new APExam(subject, score));  // use of parametrized constructor
        sc.nextLine();
    }
    sc.close(); // never forget to close Scanner

    //display information etc.
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Trouble getting size of an array in a js object inside controller

From Dev

Trouble with object array

From Dev

Having trouble getting text input working on imacro

From Dev

Trouble deep cloning an array object

From Dev

Trouble getting properties and object structured correctly

From Dev

Trouble getting an array in sets program (C)

From Dev

Trouble getting getJSON to display values from array

From Dev

MVC CodeIgniter, trouble getting array to pass to view

From Dev

MIPS user input array storing and printing trouble

From Dev

Getting NullPointerException with Object Array

From Dev

Trouble getting a game object from object pool in Unity

From Dev

Trouble with getting right value from html input using jquery

From Dev

Trouble getting RPi device data in IBM IoT input node

From Dev

Always getting value of first input element. Trouble with JQuery Ajax

From Dev

Having trouble for getting input from EditText field for Android

From Dev

Trouble copying contents of an array into another array...getting weird numbers

From Dev

javascript getting user input to an array

From Dev

Having trouble getting access to the Object in JSON from url

From Dev

Having trouble getting access to the Object in JSON from url

From Dev

javascript object array input to array to object

From Dev

Getting trouble with picking most and less valued day from an array

From Dev

Having trouble getting nested ojects from json array in python

From Dev

Trouble getting json_encode array elements into seperate jQuery variables

From Dev

Having Trouble Getting a MySQL Query Result into a PHP Array

From Dev

Trouble getting the right appearance of an array (Python3)

From Dev

Having trouble getting the rest of the numbers in an Array. Java

From Dev

Getting the length of an array inside an object

From Dev

Adding object to array and getting NullPointerException

From Dev

getting object instead of array in javascript

Related Related

  1. 1

    Trouble getting size of an array in a js object inside controller

  2. 2

    Trouble with object array

  3. 3

    Having trouble getting text input working on imacro

  4. 4

    Trouble deep cloning an array object

  5. 5

    Trouble getting properties and object structured correctly

  6. 6

    Trouble getting an array in sets program (C)

  7. 7

    Trouble getting getJSON to display values from array

  8. 8

    MVC CodeIgniter, trouble getting array to pass to view

  9. 9

    MIPS user input array storing and printing trouble

  10. 10

    Getting NullPointerException with Object Array

  11. 11

    Trouble getting a game object from object pool in Unity

  12. 12

    Trouble with getting right value from html input using jquery

  13. 13

    Trouble getting RPi device data in IBM IoT input node

  14. 14

    Always getting value of first input element. Trouble with JQuery Ajax

  15. 15

    Having trouble for getting input from EditText field for Android

  16. 16

    Trouble copying contents of an array into another array...getting weird numbers

  17. 17

    javascript getting user input to an array

  18. 18

    Having trouble getting access to the Object in JSON from url

  19. 19

    Having trouble getting access to the Object in JSON from url

  20. 20

    javascript object array input to array to object

  21. 21

    Getting trouble with picking most and less valued day from an array

  22. 22

    Having trouble getting nested ojects from json array in python

  23. 23

    Trouble getting json_encode array elements into seperate jQuery variables

  24. 24

    Having Trouble Getting a MySQL Query Result into a PHP Array

  25. 25

    Trouble getting the right appearance of an array (Python3)

  26. 26

    Having trouble getting the rest of the numbers in an Array. Java

  27. 27

    Getting the length of an array inside an object

  28. 28

    Adding object to array and getting NullPointerException

  29. 29

    getting object instead of array in javascript

HotTag

Archive