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()
Language C++ Student-Report Card Generator: create a class called student and class called course. student class...
Language C++ Student-Report Card Generator: create a class called student and class called course. student class this class should contain the following private data types: - name (string) - id number (string) - email (s) - phone number (string) - number of courses (int) - a dynamic array of course objects. the user will specify how many courses are there in the array. the following are public members of the student class: - default constructor (in this constructor, prompt the...
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...
Write a Python program that creates a class which represents a Student Grade. The class includes...
Write a Python program that creates a class which represents a Student Grade. The class includes a function that reads a text file called Course_Score.txt. A sample of the file is provided below. Each row in the file corresponds to the Last Name, First Name, ClassWork score (100), Mid-Term score (100), and Final-Exam score (100). Also include the the following functions to process the content read from the file. a. getData(): This method reads the data from a file and...
***Given a class called Student and a class called Course that contains an ArrayList of Student....
***Given a class called Student and a class called Course that contains an ArrayList of Student. Write a method called dropStudent() as described below. Refer to Student.java below to learn what methods are available.*** Course.java import java.util.*; import java.io.*; /****************************************************** * A list of students in a course *****************************************************/ public class Course{ /** collection of Students */ private ArrayList<Student> roster; /***************************************************** Constructor for objects of class Course *****************************************************/ public Course(){ roster = new ArrayList<Student>(); } /***************************************************** Remove student with the...
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...
Exercise #1: Create an abstract class called GameTester. The GameTester class includes a name for the...
Exercise #1: Create an abstract class called GameTester. The GameTester class includes a name for the game tester and a boolean value representing the status (full-time, part-time). Include an abstract method to determine the salary, with full-time game testers getting a base salary of $3000 and part-time game testers getting $20 per hour. Create two subclasses called FullTimeGameTester, PartTimeGameTester. Create a console application that demonstrates how to create objects of both subclasses. Allow the user to choose game tester type...
Question 1 (10) Create a class Student with public member variables: Student name, student number, contact...
Question 1 (10) Create a class Student with public member variables: Student name, student number, contact number, ID number. The following specifications are required:  Add init() method of the class that initializes string member variables to empty strings and numeric values to 0. (2)  Add the method populate() to the class. The method is used to assign values to the member variables of the class. (2)  Add the method display() to the class. The method is used...
JAVA Program Create a class called SoccerPlayer Create 4 private attributes: First Name, Last Name, Games,...
JAVA Program Create a class called SoccerPlayer Create 4 private attributes: First Name, Last Name, Games, and Goals Have two constructors Constructor 1 – default constructor; all values to "NONE" or zero Constructor 2 – accepts input of first name, last name, games and goals. Create get and set methods for each of the four attributes Create a method the returns a double that calculates the average goals per game This method checks for zero games played: If there are...
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.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT