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...
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...
***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...
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...
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.
Name: __________________________________________ Specifications: Create a class called WordMaker that is passed characters one at a time...
Name: __________________________________________ Specifications: Create a class called WordMaker that is passed characters one at a time and assembles them into words. As long as the characters passed to it are letters, it builds a word by placing each character on the end of a string. When a character that is not part of a word (i.e., is not a letter) is encountered, the class signals that the word is complete, and makes a string containing the word available to its...
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...
JAVA PROGRAMMING Part 1 Create a class Student, with attributes id, first name, last name. (All...
JAVA PROGRAMMING Part 1 Create a class Student, with attributes id, first name, last name. (All the attributes must be String) Create a constructor that accepts first name and last name to create a student object. Create appropriate getters and setters Create another class StudentOperationClient, that contains a main program. This is the place where the student objects are created and other activities are performed. In the main program, create student objects, with the following first and last names. Chris...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT