Question

In: Computer Science

Question(Design Java Method). There is a java code what created a "Student" class and hold all...

Question(Design Java Method).

There is a java code what created a "Student" class and hold all the books owned by the student in the inner class "Book". Please propose a new method for the Student class so that given a Student object "student", a program can find out the title of a book for which student.hasBook(isbn) returns true. Show the method code and the calls to it from a test program.

The Student class is following:

import java.lang.Integer;
import java.util.ArrayList;
import java.util.List;

class Student implements Comparable<Student> {
   private int id;
   private String name;
   private double gpa;
   private List<Book> books;

   public Student(String n, int i, double gpa) {
      name = n;
      id = i;
      this.gpa = gpa;
      books = new ArrayList<Student.Book>();
   }

   private static class Book {
      private String title;
      private String ISBN;

      public Book(String title, String ISBN) {
         super();
         this.title = title;
         this.ISBN = ISBN;
      }

      public String getTitle() { return title; }

      public void setTitle(String title) { this.title = title; }

      public String getISBN() { return ISBN; }

      public void setISBN(String ISBN) { this.ISBN = ISBN; }
   }

   public void addBook(String title, String ISBN) {
      Book book = new Book(title, ISBN);
      books.add(book);
   }

   public boolean hasBook(String ISBN) {

      for (int i = 0; i < books.size(); i++) {
         Book b = books.get(i);
         if (b.getISBN() == ISBN)
            return true;
      }
      return false;
   }

   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public double getGpa() {
      return gpa;
   }
   public void setGpa(double gpa) {
      this.gpa = gpa;
   }

   public String toString() { return "(" + name+ " " + id + " " + gpa + ")";}

   public boolean equals(Object rhs)  {   // more compact code, but still correct
      if (rhs == null || getClass() != rhs.getClass())
         return false;
      Student other = (Student) rhs;
      return id == other.id;
   }

   public int hashCode()
   { return Integer.valueOf(id).hashCode(); }

   public int compareTo(Student other)
   { return Integer.valueOf(id).compareTo(Integer.valueOf(other.id)); }
}

Solutions

Expert Solution

Here is the completed code for Student.java file as well as Test.java for testing the new method. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

// Student.java

import java.lang.Integer;

import java.util.ArrayList;

import java.util.List;

class Student implements Comparable<Student> {

                private int id;

                private String name;

                private double gpa;

                private List<Book> books;

                public Student(String n, int i, double gpa) {

                                name = n;

                                id = i;

                                this.gpa = gpa;

                                books = new ArrayList<Student.Book>();

                }

                private static class Book {

                                private String title;

                                private String ISBN;

                                public Book(String title, String ISBN) {

                                                super();

                                                this.title = title;

                                                this.ISBN = ISBN;

                                }

                                public String getTitle() {

                                                return title;

                                }

                                public void setTitle(String title) {

                                                this.title = title;

                                }

                                public String getISBN() {

                                                return ISBN;

                                }

                                public void setISBN(String ISBN) {

                                                this.ISBN = ISBN;

                                }

                }

                public void addBook(String title, String ISBN) {

                                Book book = new Book(title, ISBN);

                                books.add(book);

                }

                public boolean hasBook(String ISBN) {

                                for (int i = 0; i < books.size(); i++) {

                                                Book b = books.get(i);

                                                //always use equals method to compare Strings instead of ==

                                                if (b.getISBN().equals(ISBN))

                                                                return true;

                                }

                                return false;

                }

                /**

                * newly implemented method, given an ISBN, returns the title of the book,

                * if this student has a book with this ISBN, otherwise returns null

                *

                * @param ISBN

                *            - ISBN of book to search

                * @return the title if found, null if not

                */

                public String getTitleOfBook(String ISBN) {

                                //looping through each book

                                for (int i = 0; i < books.size(); i++) {

                                                Book b = books.get(i);

                                                //if current book's ISBN equals target, returning title of book

                                                if (b.getISBN().equals(ISBN))

                                                                return b.getTitle();

                                }

                                return null; //not exists

                }

                public int getId() {

                                return id;

                }

                public void setId(int id) {

                                this.id = id;

                }

                public String getName() {

                                return name;

                }

                public void setName(String name) {

                                this.name = name;

                }

                public double getGpa() {

                                return gpa;

                }

                public void setGpa(double gpa) {

                                this.gpa = gpa;

                }

                public String toString() {

                                return "(" + name + " " + id + " " + gpa + ")";

                }

                public boolean equals(Object rhs) { // more compact code, but still correct

                                if (rhs == null || getClass() != rhs.getClass())

                                                return false;

                                Student other = (Student) rhs;

                                return id == other.id;

                }

                public int hashCode() {

                                return Integer.valueOf(id).hashCode();

                }

                public int compareTo(Student other) {

                                return Integer.valueOf(id).compareTo(Integer.valueOf(other.id));

                }

}

//Test.java for testing new method

public class Test {

      public static void main(String[] args) {

            // creating a Student and adding some books

            Student student = new Student("Oliver", 123, 3.9);

            student.addBook("CSC 101", "ABCDEFGH");

            student.addBook("ENG 13", "1234XYZ");

            student.addBook("Programming in Java", "1010UUIJKL1");

            student.addBook("Introduction to C++", "90908765ETYU");

            // displaying if student has a book with isbn: 1010UUIJKL1, should be

            // true

            System.out.println("has book with ISBN 1010UUIJKL1: "

                        + student.hasBook("1010UUIJKL1"));

            // displaying title of a book with isbn: 1010UUIJKL1, should be

            // "Programming in Java"

            System.out.println("title of book with ISBN 1010UUIJKL1: "

                        + student.getTitleOfBook("1010UUIJKL1"));

            // displaying if student has a book with isbn: 1010101010, should be

            // false

            System.out.println("has book with ISBN 1010101010: "

                        + student.hasBook("1010101010"));

            // displaying title of a book with isbn: 1010101010, should be

            // null

            System.out.println("title of book with ISBN 1010101010: "

                        + student.getTitleOfBook("1010101010"));

      }

}

/*OUTPUT*/

has book with ISBN 1010UUIJKL1: true

title of book with ISBN 1010UUIJKL1: Programming in Java

has book with ISBN 1010101010: false

title of book with ISBN 1010101010: null


Related Solutions

In Java in previous question #1, you created a method called isDNAvalid() in the DNA class....
In Java in previous question #1, you created a method called isDNAvalid() in the DNA class. You probably looped through the entire sequence one character at a time (using charAt() method of the String class), and check if the character is 'A', 'T', 'G', or 'C'. If it is not one of these four characters, the sequence contains an invalid base. Please re-create the isDNAvalid() method using a character pattern and the regular expression to validate the DNA sequence. previous...
Required components: A controller class with Java main() method and a PaymentCalculator class to hold the...
Required components: A controller class with Java main() method and a PaymentCalculator class to hold the data and methods for the application. Scenario/Information: If you carry a balance on a credit card, it can be nice to see how long it would take to payoff the card. For this scenario, you should design a Java application the prints a credit card payment schedule. Inputs for your program should include: Customer’s name (first and last), the account number (as an integer),...
**Java** - Creating from scratch. Original code hasn't been created yet. Design a class named Octagon...
**Java** - Creating from scratch. Original code hasn't been created yet. Design a class named Octagon that extends GeometricObject class and implements the Comparable and Cloneable interface. Assume that all eight sides of the octagon are of equal size. The area can be computed using following formula: Write a test program that creates an Octagon object with side values 5 and display its area and perimeter. Create a new object using clone method and compare the two objects using compareTo...
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try...
Java Modify subclass HourlyEmployee11 and class HourlyExc (created to hold the exception) to add a "try and catch" statement to catch an exception if "empStatus == 1" hourly wage is not between $15.00/hr. and $25.00/hr. The keywords “throw” and “throws” MUST be used correctly and both keywords can be used either in a constructor or in a method. If an exception is thrown, the program code should prompt the user for the valid input and read it in. *NOTE*- I...
Java: Translate the Student class from the code provided to UML, e.g., -----------------------------_ | Student |...
Java: Translate the Student class from the code provided to UML, e.g., -----------------------------_ | Student | ------------------------------ | -lastName: String | | -firstName: String | ----------------------------- Java Code: public class Student { private String lName; private String fName; private int age; private double gpa; public Student(String lname, String fname, int age, double gpa);    public String lname();    public String fname();    public int age(); public double gpa(); public String toString()      {          return lName+ " " + fName+...
A Java question. You are given a Student class. A Student has a name and an...
A Java question. You are given a Student class. A Student has a name and an ArrayList of grades (Doubles) as instance variables. Write a class named Classroom which manages Student objects. You will provide the following: 1. public Classroom() a no-argument constructor. 2. public void add(Student s) adds the student to this Classroom (to an ArrayList 3. public String hasAverageGreaterThan(double target) gets the name of the first student in the Classroom who has an average greater than the target...
Java Question Design a class named Person and its two subclasses named Student and Employee. Make...
Java Question Design a class named Person and its two subclasses named Student and Employee. Make Faculty and Staff subclasses of Employee. A person has a name, address, phone number, and email address. A student has a class status (freshman, sophomore, junior, or senior). Define the status as a constant. An employee has an office, salary, and date hired. Use the Date class to create an object for date hired. A faculty member has office hours and a rank. A...
Java program Create a public method named saveData for a class named Signal that will hold...
Java program Create a public method named saveData for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp...
27) Consider the student class. There is a method setSemesterGrade(int grade) In that method write code...
27) Consider the student class. There is a method setSemesterGrade(int grade) In that method write code to throw a new IllegalStateException if the average is less than 0 And an IndexOutOfBoundsException if the average is > 0 28) Consider a student represented by the variable s1 and we are trying to set the average of s1. Write a try catch routine to catch either error listed above try { s1.setSemesterGrade(-30); s1.setSemesterGrade(200);
in java code In the class Hw2, write a method removeDuplicates that given a sorted array,...
in java code In the class Hw2, write a method removeDuplicates that given a sorted array, (1) removes the duplicates so that each distinct element appears exactly once in the sorted order at beginning of the original array, and (2) returns the number of distinct elements in the array. The following is the header of the method: public static int removeDuplicates(int[ ] A) For example, on input A=0, 0, 1, 1, 1, 2, 2, 3, 3, 4, your method should:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT