Question

In: Computer Science

Create a class called Student which stores • the name of the student • the grade...

Create a class called Student which stores

• the name of the student

• the grade of the student

• Write a main method that asks the user for the name of the input file and the name of the output file. Main should open the input file for reading . It should read in the first and last name of each student into the Student’s name field. It should read the grade into the grade field.

• Calculate the average of all students’ grades.

• Open the output file, for writing, and print all the students’ names on one line and the average on the next line.

• Average should only have 1 digit after the decimal

• “Average” should be left justified in a field of 15 characters. The average # should be right justified in a field of 10 spaces

Sample input:

Minnie Mouse 98.7

Bob Builder 65.8

Mickey Mouse 95.1

Popeye SailorMan 78.6

Output:

Minnie Mouse, Bob Builder, Mickey Mouse, Popeye SailorMan

Average:       84.5

How can I fix my code to get the same output

public class Student {
public static void main(String[] args)throws IOException{
Scanner k=new Scanner(System.in);
String name;
float grade;
float Average=(float) 0.0;
float sum=(float) 0.0;
  
System.out.println("Enter input file name:");
String input=k.nextLine();
System.out.println("Enter output file name:");
String output=k.nextLine();
  
PrintWriter pw = new PrintWriter("students.txt");
pw.print("Minnie Mouse 98.7\nBob Builder 65.8\nMickey Mouse 95.1\nPopeye SailorMan 78.6\n");
pw.close();
PrintWriter pw2 = new PrintWriter("students2.txt");
pw2.print("Donald Duck 77.77\nTweety Bird 55.555\nCharlie Brown 95.231\n");
pw2.close();
/* End of creating the input file */
while(k.hasNext())
{
name=k.next();
grade=k.nextFloat();
Average+=grade;
sum++;
System.out.printf("name, ", name);
}
grade=Average/sum;
System.out.printf("\n%-15s%10.1f","Average", grade);   
/* test output file */
Scanner testOutput = new Scanner(new File("average.txt"));
while(testOutput.hasNext())
System.out.println(testOutput.nextLine());
/* end of test output file */
}
}
  

Solutions

Expert Solution

Here is the completed code for this problem. 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. Thank

Note: The average will be 84.6 not 84.5. Because the actual average is 84.55, formatting to 1 digit after decimal point will automatically round it to 84.6


//Student.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class Student {
        // attributes
        private String name;
        private double grade;

        // constructor taking name and grade
        public Student(String name, double grade) {
                this.name = name;
                this.grade = grade;
        }

        // getters for name and grade

        public String getName() {
                return name;
        }

        public double getGrade() {
                return grade;
        }

        // helper method to create input files dynamically, if you want
        private static void createInputFiles() throws FileNotFoundException {
                PrintWriter pw = new PrintWriter("students.txt");
                pw.print("Minnie Mouse 98.7\nBob Builder 65.8\nMickey Mouse 95.1\nPopeye SailorMan 78.6\n");
                pw.close();
                PrintWriter pw2 = new PrintWriter("students2.txt");
                pw2.print("Donald Duck 77.77\nTweety Bird 55.555\nCharlie Brown 95.231\n");
                pw2.close();
        }

        // main method
        public static void main(String[] args) throws IOException {
                Scanner sc = new Scanner(System.in);
                String name;
                double grade, sum, avg;

                // uncomment below statement if you want to create input files
                // (students.txt, students2.txt) dynamically.

                // createInputFiles();

                // asking, reading input & output file names

                System.out.println("Enter input file name:");
                String inFile = sc.nextLine();

                System.out.println("Enter output file name:");
                String outFile = sc.nextLine();

                // creating a list of Student objects
                ArrayList<Student> students = new ArrayList<Student>();

                // reinitializing scanner to read from file
                sc = new Scanner(new File(inFile));
                // looping through file
                while (sc.hasNext()) {
                        // reading next two strings to create single name
                        name = sc.next() + " " + sc.next();
                        // reading next number to store grade
                        grade = sc.nextDouble();
                        // creating a Student object with this name and grade, adding to
                        // list
                        students.add(new Student(name, grade));
                }
                // closing file
                sc.close();

                sum = 0;
                // opening output file
                PrintWriter writer = new PrintWriter(new File(outFile));
                // looping through the list
                for (int i = 0; i < students.size(); i++) {
                        // adding grade to sum
                        sum += students.get(i).getGrade();
                        // printing student name to output file followed by ', ' if
                        // necessary
                        writer.print(students.get(i).getName());
                        if (i != students.size() - 1) {
                                writer.print(", ");
                        }
                }
                // finding average
                avg = sum / students.size();
                // displaying average with proper formatting. (label is formatted with
                // 15 character wide field left justified, average formatted to 1 digit
                // after decimal, in a field of length 10, right justified)
                writer.printf("\n%-15s%10.1f\n", "Average:", avg);
                // closing file, saving changes
                writer.close();
        }
}

/*OUTPUT*/

Enter input file name:
students.txt
Enter output file name:
output.txt

/*output.txt*/

Minnie Mouse, Bob Builder, Mickey Mouse, Popeye SailorMan
Average:             84.6

Related Solutions

Create a student class that stores name, registration number and percentage, grade. Add member functions -...
Create a student class that stores name, registration number and percentage, grade. Add member functions - Read( string n, int r, float p): Read function that accepts parameter - Display(): To display student’s information - CalculateGrade()
Create a class called Student. Include the following instance variables: name, address, phone, gpa Create all...
Create a class called Student. Include the following instance variables: name, address, phone, gpa Create all of the methods required for a standard user defined class: constructors, accessors, mutators, toString, equals Create the client for testing the Student class Create another class called CourseSection Include instance variables for: course name, days and times course meets (String), description of course, student a, student b, student c (all of type Student) Create all of the methods required for a standard user defined...
Animal class Create a simple class called Animal instantiated with a name and a method toString...
Animal class Create a simple class called Animal instantiated with a name and a method toString which returns the name. Cat class Create a simple class Cat which extends Animal, but adds no new instance variable or methods. RedCat class Create a simple class RedCat which extends Cat, but adds no new instance variable or methods. WildCardTester class Create a class with the main method and methods addCat, deleteCat and printAll as follows. addCat method Has two parameters, an ArrayList...
C++ HW Aim of the assignment is to write classes. Create a class called Student. This...
C++ HW Aim of the assignment is to write classes. Create a class called Student. This class should contain information of a single student. last name, first name, credits, gpa, date of birth, matriculation date, ** you need accessor and mutator functions. You need a constructor that initializes a student by accepting all parameters. You need a default constructor that initializes everything to default values. write the entire program.
Create a C structure which stores information about a student. Each student should be represented by...
Create a C structure which stores information about a student. Each student should be represented by a student ID (integer), first name, last name, day, month and year of birth, and program code (string). Write a C program which creates an array of 100 of these structures, then prompts the user to enter data from the keyboard to fill the array. If an ID of 0 is entered, data entry should finish, and the list of students should be printed...
IN JAVA PLEASE Create a class called Child with an instance data values: name and age....
IN JAVA PLEASE Create a class called Child with an instance data values: name and age. a. Define a constructor to accept and initialize instance data b. include setter and getter methods for instance data c. include a toString method that returns a one line description of the child
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name...
in Java, Create a class called EMPLOYEE that includes three instance variables – a first name (type String), a last name (type String) and a monthly salary (double). Provide a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, do not set its value. Write a test app names EmployeeTest that demonstrates class EMLOYEE’s capabilities. Create two EMPLOYEE objects and display each object’s yearly...
Write a C++ programs to: 1. Create a class called Student with four (4) private member...
Write a C++ programs to: 1. Create a class called Student with four (4) private member variables, name (string), quiz, midterm, final (all double type); 2. Include all necessary member functions for this class (at least 1 constructor, 1 get function, and 1 grading function – see #6); 3. Declare three (3) objects of Student type (individual or array); 4. Read from the keyboard three (3) sets of values of name, quiz, midterm, final and assign them to each object;...
follow pseudo 1) Create class called Node Declare private integer called data (or any other name)...
follow pseudo 1) Create class called Node Declare private integer called data (or any other name) Declare private Node called link (or any other name) 2) Declare constructor Should be public (ex: Node) where: link is equal to null data is equal to zero 3) Declare another constructor public Node with parameters integer d, Node n where: data is equal to d link is equal to n 4) Declare function to set link to next Node link equal to n...
Create a class called Vehicle that includes four instance variables:      name, type,     tank size and...
Create a class called Vehicle that includes four instance variables:      name, type,     tank size and average petrol consumption. Provide 2 constructors, the first takes name and type as parameter, the second takes four parameters for the four instance variables. (2 pt) Provide also a method called distancePerTank that calculate the average distance that a vehicle can travel if the tank is full (multiplies the tank size by the average petrol consumption), then returns the value. (2 pt) Provide a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT