Question

This is an optional assignment and is worth a maximum of 100 points. Load an array...

This is an optional assignment and is worth a maximum of 100 points. Load an array of 100 student numbers from the included file Students.txt. (It is located with the other class files) Prompt the user to search for a student

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class StudentGroup 
{
        // Maximum number of students stored in array
        private final static int MAX_STUDENTS = 200;
        
        // Instance variables
        private Student[] students;     // array of Student objects
        private int numStudents;        // number of actual objects in array

        /** Constructs an empty student group with capacity for MAX_STUDENTS
         */
        public StudentGroup() 
        {
                students = new Student[MAX_STUDENTS];
                numStudents = 0;
        }
        
        /** Constructs a student group with capacity for MAX_STUDENTS
         *  and populates it with the student data found in the given file
         *  @param fileName name of file containing student data
         */
        public StudentGroup(String fileName) 
        {
                students = new Student[MAX_STUDENTS];
                numStudents = 0;
                readFile(fileName);
        }

        /** Searches the students[] via a linear search to find a student object based on its name
         *  @param name the name of the student that is being searched for
         *      @return the student object with the matching name
         */

        public Student findByName(String name) 
        {
                Student stu = null;
                for (int x = 0; x < numStudents; x++)
                {
                        if (students[x].getName().equals(name))
                        {
                                stu = students[x];
                        }

                }
                return stu;
                
        }

        /** 
         * Sorts the students[] by insertion sort
         */
        
        public void sortByName() 
        {
                for (int x = 1; x < numStudents; x++)
                {
                        Student key = students[x]; //defines the key to compare agaisnt
                        int location = x;
                        while (location > 0 && key.getName().compareTo(students[location - 1].getName()) < 0)
                        {
                                students[location] = students[location - 1]; //swaps location
                                location--;
                        }
                        students[location] = key; //defines new key
                }
        }

        /**
         * Sorts the students[] by a selection sort
         */

        public void sortByID() 
        {
                for (int x = 0; x < numStudents - 1; x++)
                {
                        int minIndex = x; //sets the minimum index
                        for (int y = x + 1; y < numStudents; y++)
                        {
                                if (students[y].getID() < students[minIndex].getID())
                                {
                                        minIndex = y; //if the student's ID at index y is less than the student's ID at the minimum index, let y be the new minIndex
                                }
                        }
                        Student temp = students[x];      
                        students[x] = students[minIndex]; //swaps the students
                        students[minIndex] = temp;
                }
        }

        /** Searches the students[] by using a binary search and finds a student based on matching ID number. Search returns the student if found, otherwise it returns null.
         * @param id the id number to be seached for
         * @return student object with matching ID number
         */

        public Student findByID(int id) 
        {
                int low = 0;
                int high = numStudents - 1;
                while (low <= high)
                {
                        int middle = (low + high) / 2;
                        if (students[middle].getID() == id)
                        {
                                return students[middle];
                        }
                        else if(id < students[middle].getID())
                        {
                                high = middle - 1;
                        }
                        else
                        {
                                low = middle + 1;
                        }
                }
                return null;
        }

        /** Provides the group of students
         *  @return the group of students as a string
         */
        public String toString() 
        {
                String str = "[";
                for (int k = 0; k < numStudents; k++) 
                {
                        str += students[k].toString();
                        if (k == numStudents-1) 
                                str += "]";
                        else
                                str += ",\n ";
                }
                return str;
        }

        /** Reads student entries from a given file and stores them in the array
         *  @param fileName name of file containing student data in format
         *         LAST<space>FIRST<space>ID<space>GPA
         */
        private void readFile(String fileName) 
        {
                try 
                {
                        // Open file for reading
                        Scanner scan = new Scanner(new FileReader(fileName));
                        
                        // Continue reading and adding students until there are no more entries
                        // Entries are in form LAST<space>FIRST<space>ID<space>GPA
                        while (scan.hasNextLine()) 
                        {                                               
                                String inputStr = scan.nextLine();
                                Scanner strScan = new Scanner(inputStr);
                                String lastName = strScan.next();
                                String firstName = strScan.next();
                                int id = strScan.nextInt();
                                double gpa = strScan.nextDouble();

                                Student stu = new Student(lastName, firstName, id, gpa);
                                students[numStudents] = stu;
                                numStudents++;
                        }
                        scan.close();
                } 
                catch (IOException e) 
                {
                        System.out.println("Error reading from file " + fileName +
                                                                          "\nError:  " + e.getMessage());
                } 
                catch (Exception e) 
                {
                        System.out.println("Error reading from file " + fileName +
                                                                          "\nError:  " + e.getMessage());
                }
        }
}

Studentgroup.java

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class StudentGroup
{
// Maximum number of students stored in array
private final static int MAX_STUDENTS = 200;

// Instance variables
private Student[] students; // array of Student objects
private int numStudents; // number of actual objects in array

/** Constructs an empty student group with capacity for MAX_STUDENTS
*/
public StudentGroup()
{
students = new Student[MAX_STUDENTS];
numStudents = 0;
}

/** Constructs a student group with capacity for MAX_STUDENTS
* and populates it with the student data found in the given file
* @param fileName name of file containing student data
*/
public StudentGroup(String fileName)
{
students = new Student[MAX_STUDENTS];
numStudents = 0;
readFile(fileName);
}

/** Searches the students[] via a linear search to find a student object based on its name
* @param name the name of the student that is being searched for
* @return the student object with the matching name
*/

public Student findByName(String name)
{
Student stu = null;
for (int x = 0; x < numStudents; x++)
{
if (students[x].getName().equals(name))
{
stu = students[x];
}

}
return stu;

}

/**
* Sorts the students[] by insertion sort
*/

public void sortByName()
{
for (int x = 1; x < numStudents; x++)
{
Student key = students[x]; //defines the key to compare agaisnt
int location = x;
while (location > 0 && key.getName().compareTo(students[location - 1].getName()) < 0)
{
students[location] = students[location - 1]; //swaps location
location--;
}
students[location] = key; //defines new key
}
}

/**
* Sorts the students[] by a selection sort
*/

public void sortByID()
{
for (int x = 0; x < numStudents - 1; x++)
{
int minIndex = x; //sets the minimum index
for (int y = x + 1; y < numStudents; y++)
{
if (students[y].getID() < students[minIndex].getID())
{
minIndex = y; //if the student's ID at index y is less than the student's ID at the minimum index, let y be the new minIndex
}
}
Student temp = students[x];     
students[x] = students[minIndex]; //swaps the students
students[minIndex] = temp;
}
}

/** Searches the students[] by using a binary search and finds a student based on matching ID number. Search returns the student if found, otherwise it returns null.
* @param id the id number to be seached for
* @return student object with matching ID number
*/

public Student findByID(int id)
{
int low = 0;
int high = numStudents - 1;
while (low <= high)
{
int middle = (low + high) / 2;
if (students[middle].getID() == id)
{
return students[middle];
}
else if(id < students[middle].getID())
{
high = middle - 1;
}
else
{
low = middle + 1;
}
}
return null;
}

/** Provides the group of students
* @return the group of students as a string
*/
public String toString()
{
String str = "[";
for (int k = 0; k < numStudents; k++)
{
str += students[k].toString();
if (k == numStudents-1)
str += "]";
else
str += ",\n ";
}
return str;
}

/** Reads student entries from a given file and stores them in the array
* @param fileName name of file containing student data in format
*         LAST<space>FIRST<space>ID<space>GPA
*/
private void readFile(String fileName)
{
try
{
// Open file for reading
Scanner scan = new Scanner(new FileReader(fileName));

// Continue reading and adding students until there are no more entries
// Entries are in form LAST<space>FIRST<space>ID<space>GPA
while (scan.hasNextLine())
{
String inputStr = scan.nextLine();
Scanner strScan = new Scanner(inputStr);
String lastName = strScan.next();
String firstName = strScan.next();
int id = strScan.nextInt();
double gpa = strScan.nextDouble();

Student stu = new Student(lastName, firstName, id, gpa);
students[numStudents] = stu;
numStudents++;
}
scan.close();
}
catch (IOException e)
{
System.out.println("Error reading from file " + fileName +
"\nError: " + e.getMessage());
}
catch (Exception e)
{
System.out.println("Error reading from file " + fileName +
"\nError: " + e.getMessage());
}
}
}

/**
 * StudentGroupTest.java
 * Test the StudentGroup class
 */

public class StudentGroupTest 
{
        public static void main(String[] args) 
        {
                StudentGroup apcs1 = new StudentGroup("apcs1.txt");
                System.out.println("Students\n" + apcs1 + "\n");

                
                // Test findByName, a linear search
                System.out.println("Searching by name:");
                Student small = apcs1.findByName("Fry, Small");
                if (small == null)
                        System.out.println("Unable to find Fry, Small");
                else
                        System.out.println("Found:  " + small.toString());

                Student big = apcs1.findByName("Dude, Big");
                if (big == null)
                        System.out.println("Unable to find Dude, Big");
                else
                        System.out.println("Found:  " + big.toString());
                System.out.println();


                
                // Test sortByName, an Insertion Sort
                apcs1.sortByName();
                System.out.println("Students sorted by name\n" + 
                                                                        apcs1 + "\n");
        
                

        
                // Test sortByID, a Selection Sort
                apcs1.sortByID();
                System.out.println("Students sorted by ID\n" + 
                                                                        apcs1 + "\n");


                
                // Test findByID, a binary search
                System.out.println("Searching by ID:");
                Student stu5927 = apcs1.findByID(5927);
                if (stu5927 == null)
                        System.out.println("Unable to find student with ID 5927");
                else
                        System.out.println("Found:  " + stu5927.toString());

                Student stu1111 = apcs1.findByID(1111);
                if (stu1111 == null)
                        System.out.println("Unable to find student with ID 1111");
                else
                        System.out.println("Found:  " + stu1111.toString());
                System.out.println();
        
        }
}

apcs1.txt

Wolf Mighty 2933 4.521
Smart Geraldine 1234 3.5
Fry Small 1524 3.9
Curve Belo 9342 2.5
Passing Ima 3927 2.75
Failing Huzza 5927 1.85
Average Justine 6322 3.2
Pants Smarty 1523 4.239
Enovera Marge 3926 3.999
Add a comment
Know the answer?
Add Answer to:
This is an optional assignment and is worth a maximum of 100 points. Load an array...
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
  • Stuck on this computer science assignment Write a program that demonstrates binary searching through an array...

    Stuck on this computer science assignment Write a program that demonstrates binary searching through an array of strings and finding specific values in an corresponding parallel double array. In all cases your output should exactly match the provided solution.o. Provided files: Assignment.cpp - starter assignment with function prototypes companies.txt - file for program to read. earnings.txt - file for program to read. Input1.txt Input2.txt - Test these inputs out manually, or use stream redirection Input3.txt - These inputs are based...

  • Could anyone please help with this Python code assignment? In this programming assignment you are to...

    Could anyone please help with this Python code assignment? In this programming assignment you are to create a program called numstat.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The count of how many numbers are in the file. The average of the numbers. The average is the sum of the numbers divided by how many there are. The maximum value. The...

  • Please write a Java program that does the following: Create an array of 100 integers. Store...

    Please write a Java program that does the following: Create an array of 100 integers. Store 100 random integers (between 1 and 100) in the array. Print out the elements of the array. Sort the array in ascending order. Print out the sorted array. Prompt the user to enter a number between 1 and 100. Search the array for that number and then display "Found" or "Not Found" message. Display each number from 1 to 100 and the number of...

  • you Wlluk It is also expected that This assignment is worth 100 points and is due...

    you Wlluk It is also expected that This assignment is worth 100 points and is due before class on January 30 D Question 5 This formula is known as: Perpetuity Growth Formula # Reinvestment Equation ROIC 1 Previous is also expected that you will work on this assignment by yourself. is assignment is worth 100 points and is due before class on January 30th. D Question 6 All of the following are methods of corporate valuation, EXCEPT: O Adjusted Present...

  • This assignment is about array operations. You need to count a specific items in an array....

    This assignment is about array operations. You need to count a specific items in an array. Steps to follow are here: • Create an array with 1000 items and fill it with random numbers from the range of -100, 100 (including - 100 and 100). . In your program asks user to enter a number, K. • Search this number and print the frequency (how many) of this K is found in the array. • Ask another number, and so...

  • Array Class Assignment

    This is a two-part assignment. It is better to submit the files for both parts when you are done than to submit part 1 first and part 2 later.In the Array.h file includes the class definition and member functions implementations.PART 1Write And Test An Array Class [Array.TestDriver.cpp] Write a data structures class. The resulting class can be used in any program in place of a C++ array, in case you want the advantages of range safety and built-in size tracking.Requirements....

  • Write a menu based program implementing the following functions: (0) Write a function called displayMenu that...

    Write a menu based program implementing the following functions: (0) Write a function called displayMenu that does not take any parameters, but returns an integer representing your user's menu choice. Your program's main function should only comprise of the following: a do/while loop with the displayMenu function call inside the loop body switch/case, or if/else if/ ... for handling the calls of the functions based on the menu choice selected in displayMenu. the do/while loop should always continue as long...

  • C++ code The assignment has two input files: • LSStandard.txt • LSTest.txt The LSStandard.txt file contains...

    C++ code The assignment has two input files: • LSStandard.txt • LSTest.txt The LSStandard.txt file contains integer values against which we are searching. There will be no more than 100 of these. The LSTest.txt file contains a set of numbers that we are trying to locate within the standard data set. There will be no more than 50 of these. Read both files into two separate arrays. Your program should then close both input files. All subsequent processing will be...

  • cis 112 (java reqire to use JGRASP) Searching and Sorting Assignment This is a non-object oriented...

    cis 112 (java reqire to use JGRASP) Searching and Sorting Assignment This is a non-object oriented assignment. This assignment is due at the start of class on July 16, Create a program that populates and array with 100 random integers between 0 and 99. Then print out the array. Then prompt the user for a number, and do a sequential search on the unsorted array and return whether or not the number was in the array. Then sort the array...

  • Hello there, So I got an assignment that I just cant get further with. So trying...

    Hello there, So I got an assignment that I just cant get further with. So trying to start from scratch again.. So im supposed to make a class with a UML aswell and a main file. This is how far ive came, https://imgur.com/a/MGqUN , Thats the car class code and the UML. This is the assignment Make a program where you can handle different cars at a car company. The user should be able to choose do the following: a)...

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
ADVERTISEMENT