Question

Copy the entire program 9A and paste it into this one. Be sure to change the...

Copy the entire program 9A and paste it into this one. Be sure to change the class name to 9B.

Use descriptive variable names in camel-case with the first letter in lowercase.

In the Student class, change the public attributes firstName and lastName to private ones.

In the Student class, add getters and setters called getFirstName, getLastName, setFirstName, setLastName for the two attributes.

In the Student class, add a constructor for the Student class that accepts two Strings, one parameter that you will assign to firstName and the other parameter that you will assign to lastName. If you want, you can call your parameters firstName and lastName just like the attribute names, but if you do, you will have to call your attribute names this.firstName and this.lastName within the constructor so that the compiler will know which firstName is the parameter and which is the attribute. If you call the parameters by some other names like fn and ln, or firstNameInit and lastNameInit, then you don’t have to use the “this” modifier within your constructor. Normally, fn is NOT a good variable name because it’s not very descriptive, but in a constructor, there are only a few lines of code, so it should be obvious what these short parameter names stand for, and this is common in the real world. I personally prefer something like firstNameInit, but I’m a purist.

You could set each attribute here, but it would be better to call both of your setters. Here is one of my setter calls in my constructor:

setFirstName(firstNameInit);

In main, where you called the default constructor, call your new constructor and pass firstName and lastName as arguments, then you won’t need the next two lines where you made the assignments to the attributes.

In your print method, you won’t be able to access the attributes directly anymore, so you need to comment out that line with the print statement and redo it by calling the getter methods:

System.out.printf("%2d. %s, %s\n", i+1, students[i].getLastName(), 

                  students[i].getFirstName());

Get all this working before moving on.

Now comment out the printf lines you just made and replace with this line:

System.out.printf("%2d. %s\n", i+1, students[i].toString());

Note that you only need ONE %s in the format specifier now.

Get this working before moving on.

Now comment out those lines you just made and replace with this line:

System.out.printf("%2d. %s\n", i+1, students[i]);

The reason this still works is that when you try to print something into a String, the compiler automatically checks to see whether there is a toString method for this class, and if so, it replaces it there for you.

Run it with the Sample Data and make your screen prints and the other sections of the Word file.

Please don’t stay completely stuck for much over an hour without contacting the instructor.

Sample Runs:

Please enter the maximum number of students: 8

First name (enter period . to quit): Luke

Last name: Skywalker

First name (enter period . to quit): Darth

Last name: Vader

First name (enter period . to quit): Han

Last name: Solo

First name (enter period . to quit): R2D2

Last name: Droid

First name (enter period . to quit): 3CPO

Last name: Droid

First name (enter period . to quit): .

1. Skywalker   , Luke

2. Vader       , Darth

3. Solo        , Han

4. Droid       , R2D2

5. Droid       , 3CPO

1. Droid       , 3CPO

2. Droid       , R2D2

3. Skywalker   , Luke

4. Solo        , Han

5. Vader       , Darth

Here's 9A

public class Student {
public String firstName; // first name
public String lastName; // last name

public Student(String first, String last) {
firstName = firstName;
lastName = lastName;
}

public String toString() {

return String.format ("%-12s, %-12s", firstName, lastName);


}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Student9B.java

//Program saved as Student9B
public class Student9B {
   //private member variables
   private String firstName;   
private String lastName;   
  
//constructor that sets firstname and lastname
Student9B(String firstNameInit, String lastNameInit)
{
setFirstName(firstNameInit);
setLastName(lastNameInit);
}
  
//setter methods
//method to set firstname
public void setFirstName(String firstNameInit)
{
   this.firstName = firstNameInit;
}
  
//method to set lastname
public void setLastName(String lastNameInit)
{
   this.lastName = lastNameInit;
}
  
//getter methods
//method that returns firstname
public String getFirstName()
{
   return this.firstName;
}
//method that returns lastname
public String getLastName()
{
   return this.lastName;
}
  
public void sort(Student9B[] students,int count)
{
   //loop through the students array
           for(int i=0;i<=count;i++)
           {
               for(int j=i+1;j<=count-1;j++)
               {
                   //comparing the elements
                   int result = students[i].getLastName().compareTo(students[j].getLastName());
                   if(result>0){
                       //swapping in array
                       Student9B temp=students[i];
                       students[i]=students[j];
                       students[j]=temp;
                   }

               }

           }
}
  
//override toString method
public String toString() {
return String.format ("%-12s, %-12s", getLastName(), getFirstName());
  
}
}

Student9BDriver.java

import java.util.Scanner;

public class Student9BDriver {

   public static void main(String[] args) {
       Scanner input=new Scanner(System.in);
       String firstName,lastName;
       boolean repeat = true;
       int maxStudents;

       //prompt and read maximum number of students
       System.out.print("Please enter the maximum number of students: ");
       maxStudents = input.nextInt();

       //create an array of student objects
       Student9B[] students = new Student9B[maxStudents];
       input.nextLine();
       int count=0;

       //read the data from the user until the maximum nuber is reached or the user quits
       do
       {
           //prompt and read firstname
           System.out.print("First name (enter period . to quit): ");
           firstName = input.nextLine();
           //if user entered '.' exit the loop by setting repeat to false
           if(firstName.equals("."))
           {
               repeat = false;
           }
           else
           {
               //else prompt and read the lastname
               System.out.print("Last name: ");
               lastName = input.nextLine();
               //set the firstname and lastname to the object at index count
               students[count] = new Student9B(firstName, lastName);
               count++; //increment count, count will have actual number of data inserted
           }
       }while(repeat && count<maxStudents);

       System.out.println();
       //print the students names
       for(int i=0;i<count;i++ )
       {
           System.out.printf("%2d. %s\n", i+1, students[i]);
       }

       //sort the students based on last name
       sortStudentNames(students, count);
       System.out.println();

       //print the sorted list of students
       for(int i=0;i<count;i++ )
       {
           System.out.printf("%2d. %s\n", i+1, students[i].toString());
       }
       input.close();
   }

   //method that takes the students names and sorts them
   public static void sortStudentNames(Student9B[] students,int count)
   {
       //loop through the students array
       for(int i=0;i<=count;i++)
       {
           for(int j=i+1;j<=count-1;j++)
           {
               //comparing the students based on lastname
               int res = students[i].getLastName().compareTo(students[j].getLastName());
               if(res>0)
               {
                   //swap the students
                   Student9B temp=students[i];
                   students[i]=students[j];
                   students[j]=temp;
               }

           }

       }
   }

}

Output:

Console X <terminated> Student9BDriver [Java Application] C:\Program Files\N Please enter the maximum number of students: 8 F

Add a comment
Know the answer?
Add Answer to:
Copy the entire program 9A and paste it into this one. Be sure to change the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • read the code and comments, and fix the program by INSERTING the missing code in Java...

    read the code and comments, and fix the program by INSERTING the missing code in Java THank you please import java.util.Scanner; public class ExtractNames { // Extract (and print to standard output) the first and last names in "Last, First" (read from standard input). public static void main(String[] args) { // Set up a Scanner object for reading input from the user (keyboard). Scanner scan = new Scanner (System.in); // Read a full name from the user as "Last, First"....

  • In c++ redefine the class personType to take advantage of the new features of object-oriented design...

    In c++ redefine the class personType to take advantage of the new features of object-oriented design that you have learned, such as operator overloading, and then derive the class customerType. personType: #include <string> using namespace std; class personType { public: void print() const; //Function to output the first name and last name //in the form firstName lastName.    void setName(string first, string last); //Function to set firstName and lastName according to the //parameters. //Postcondition: firstName = first; lastName = last...

  • JAVA PROGRAMMING In this final review lab from our intro course, use the Name class you...

    JAVA PROGRAMMING In this final review lab from our intro course, use the Name class you created in the previous lab. In this lab, create a Student class with the following class variable: Student name: Name (Note: Name is a datatype) Student Id: String Create the getter and setter methods. In addition to these methods, create a toString() method, which overrides the object class toString() method. This override method prints the current value of any of this class object. Complete...

  • HospitalEmployee Inheritance help please. import java.text.NumberFormat; public class HospitalEmployee {    private String empName;    private...

    HospitalEmployee Inheritance help please. import java.text.NumberFormat; public class HospitalEmployee {    private String empName;    private int empNumber;    private double hoursWorked;    private double payRate;       private static int hospitalEmployeeCount = 0;    //-----------------------------------------------------------------    // Sets up this hospital employee with default information.    //-----------------------------------------------------------------    public HospitalEmployee()    { empName = "Chris Smith"; empNumber = 9999; hoursWorked = 0; payRate =0;               hospitalEmployeeCount++;    }       //overloaded constructor.    public HospitalEmployee(String eName,...

  • Introduction In this lab, you will be working with three classes: Person, Student, and Roster. Person...

    Introduction In this lab, you will be working with three classes: Person, Student, and Roster. Person and Student represent individuals with a first and last name as String class variables, and Student has an additional int class variable that represents a ID number. The Roster class represents a group of people that are objects of either the Person or Student class. It contains an ArrayList. The Person class has been completed for you with class variables, a constructor, and a...

  • Write a class called Course_xxx that represents a course taken at a school. Represent each student...

    Write a class called Course_xxx that represents a course taken at a school. Represent each student using the Student class from the Chapter 7 source files, Student.java. Use an ArrayList in the Course to store the students taking that course. The constructor of the Course class should accept only the name of the course. Provide a method called addStudent that accepts one Student parameter. Provide a method called roll that prints all students in the course. Create a driver class...

  • Assignment 4 Java You are required, but not limited, to turn in the following source files:...

    Assignment 4 Java You are required, but not limited, to turn in the following source files: Assignment4.java Club.java President.java New Skills to be Applied In addition to what has been covered in previous assignments, the use of the following items, discussed in class, will probably be needed: Classes Instance Objects Accessors/Mutators(Modifiers) methods Visibility Modifiers (Access specifier) - public, private, etc. Encapsulation concept Aggregation relationship between classes Program Description The following is the description of Assignment4 class. The driver program will...

  • In Java Programming Complete the Code that remains to be implemented follow the guide lines here...

    In Java Programming Complete the Code that remains to be implemented follow the guide lines here and finish what code remains name of program class Student.java package course; public class Student { private String firstName; private String lastName; private Address homeAddress; private Address schoolAddress; private double[] testScores; // Four parameter constructor public Student(String firstName, String lastName, Address homeAddress, Address schoolAddress) { // Call the seven parameter constructor. Pass zeros for the three grades } // Five parameter constructor public Student(String...

  • DUE TODAY: Need Help with my ASP NET quiz 1.) [________________] attribute is added to ensure...

    DUE TODAY: Need Help with my ASP NET quiz 1.) [________________] attribute is added to ensure two properties on a model object have the same value. 2.) What is the purpose of the following annotation? [StringLength (120, MinimumLength=10)] public string Firstname {get; set} public string Lastname {get;set;} a. FirstName and LastName can be of length 160 characters b. FirstName and LastName can be of length 10 characters c. FirstName can be of length between 10 and 120 character s d....

  • JAVA This PoD, builds off the Book class that you created on Monday (you may copy...

    JAVA This PoD, builds off the Book class that you created on Monday (you may copy your previously used code). For today’s problem, you will add a new method to the class called lastName() that will print the last name of the author (you can assume there are only two names in the author name – first and last). You can use the String spilt (“\s”) method that will split the String by the space and will return an array...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT