Question

In: Computer Science

Your task is to modify the program from the Java Arrays programming assignment to use text...

Your task is to modify the program from the Java Arrays programming assignment to use text files for input and output. I suggest you save acopy of the original before modifying the software. Your modified program should: contain a for loop to read the five test score into the array from a text data file. You will need to create and save a data file for the program to use. It should have one test score on each line of the file. You can type and save the text file with any text editor, such as Notepad or Notepad++. NotePad++ is a good program to have on your computer, It can be downloaded freely from: https://notepad-plus-plus.org (Links to an external site.) It should be saved or copied to the same folder as your Java source code file within you Intellij project. Contain a second for loop, calculate the average score, highest score, and lowest score in the array. This part of your program does not need to change from the previous assignment. output the results to a new text file. You can decide the name of the file. You should only use a local file name and the file will then be created in your IntelliJ project folder.

Your task is to modify the program from the Java Text files programming assignment to contain several methods for different parts of the program.I suggest you save a copy of the original before modifying the software.

Your modified program should have the following six methods:

  • a method with a for loop to read the five test score into the array from a text data file. The array should be declared in the main method and passed as a parameter to this method.
  • three separate methods to each calculate and return one of the following: the average score, highest score, and lowest score . Each method should contain a for loop to calculate and return one of the values to the main method. You can copy and edit he existing loop form the previous program for each of these methods.
  • a method to output the results to a new text file, as the main method did in the previous program. You basically need to move the code to do this into a new method.
  • the main method, which has the necessary variables and which calls the other methods as needed, passing values to those methods and receiving returned value from the methods as needed.

Unlike Python functions, methods do not need to appear before they are called in a program file. In fact, it is common practice in Java to put the main() method as the first method in Java program, similar to what is done in the payMethods sample program in the chapter.

Solutions

Expert Solution

/*
* The java program that reads input file scores.txt that contains the 5 scores. Then find the average score, highest score and lowest score. Then write the data to the new file , output.txt.
* */

//Main.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main
{
   public static void main(String[] args)
   {
       String inputFile="scores.txt";
       int[] nums=new int[5];
       int location=0;
       float total_score=0;
       float average_score=0;
       float highest_score=0;
       float lowest_score=0;
       Scanner filereader=null;
       try
       {
           //Open file for reading input file, scores.txt
           filereader=new Scanner(new File(inputFile));
           //read file until the end of the file is reached and location value is less than 5
           while(filereader.hasNextLine() && location<nums.length)
           {
               //parset to integer value
               nums[location]=Integer.parseInt(filereader.nextLine());
               //increment the location
               location++;
           }
           filereader.close();
           //Assume the first element is highest score
           highest_score=nums[0];
           //Assume the first element is lowest score
           lowest_score=nums[0];
           for (int i = 1; i < nums.length; i++)
           {
               total_score=total_score+nums[i];
               if(nums[i]>highest_score)
                   highest_score=nums[i];
               if(nums[i]<lowest_score)
                   lowest_score=nums[i];
           }
           //calculate the average score
           average_score=total_score/nums.length;
           System.out.printf("Average score : %.2f\n",average_score);
           System.out.printf("Highest score : %.2f\n",highest_score);
           System.out.printf("Lowest score : %.2f\n",lowest_score);

           //Create a variable of PrintWriter class
           PrintWriter filewriter=null;
           try
           {
               //Create a PrintWriter file object of file output.txt file
               filewriter=new PrintWriter(new File("output.txt"));
               //write data to the output.txt
               filewriter.printf("Average score : %.2f\r\n",average_score);
               filewriter.printf("Highest score : %.2f\r\n",highest_score);
               filewriter.printf("Lowest score : %.2f\r\n",lowest_score);
               //close the PrintWriter file object
               filewriter.close();
           }
           catch (Exception e)
           {
               System.out.println("Exception");
           }
       }
       catch (FileNotFoundException e)
       {
           System.out.println(inputFile+" file not found...");
       }
   }
} //end of the class

------------------------------------------------------------------------------------------------------------------------------

Input file : scores.txt

85
99
96
95
75

------------------------------------------------------------------------------------------------------------------------------

Sample Output:

Average score : 73.00
Highest score : 99.00
Lowest score : 75.00

------------------------------------------------------------------------------------------------------------------------------

output.txt


Related Solutions

CS 1102 Unit 5 – Programming AssignmentIn this assignment, you will again modify your Quiz program...
CS 1102 Unit 5 – Programming AssignmentIn this assignment, you will again modify your Quiz program from the previous assignment. You will create an abstract class called "Question", modify "MultipleChoiceQuestion" to inherit from it, and add a new subclass of "Question" called "TrueFalseQuestion". This assignment will again involve cutting and pasting from existing classes. Because you are learning new features each week, you are retroactively applying those new features. In a typical programming project, you would start with the full...
Java Programming For this assignment, you should modify only the User.java file. Make sure that the...
Java Programming For this assignment, you should modify only the User.java file. Make sure that the InsufficientFundsException.java file is in the same folder as your User.java File. To test this program you will need to create your own "main" function which can import the User, create an instance and call its methods. One of the methods will throw an exception in a particular circumstance. This is a good reference for how throwing exceptions works in java. I would encourage you...
The assignment: C++ program or Java You need to use the following programming constructs/data structures on...
The assignment: C++ program or Java You need to use the following programming constructs/data structures on this assignment. 1. A structure named student which contains:   a. int ID; student id; b. last name; // as either array of char or a string c. double GPA;    2. An input file containing the information of at least 10 students. 3. An array of struct: read the student information from the input file into the array. 4. A stack: you can use the...
Java programming: Save the program as DeadlockExample.java   Run the program below.  Note whether deadlock occurs.  Then modify the...
Java programming: Save the program as DeadlockExample.java   Run the program below.  Note whether deadlock occurs.  Then modify the program to add two more threads: add a class C and a class D, and call them from main.  Does deadlock occur? import java.util.concurrent.locks.*; class A implements Runnable {             private Lock first, second;             public A(Lock first, Lock second) {                         this.first = first;                         this.second = second;             }             public void run() {                         try {                                     first.lock();                                     System.out.println("Thread A got first lock.");                                     // do something                                     try {                                                 Thread.sleep( ((int)(3*Math.random()))*1000);...
Java program In this assignment you are required to create a text parser in Java/C++. Given...
Java program In this assignment you are required to create a text parser in Java/C++. Given a input text file you need to parse it and answer a set of frequency related questions. Technical Requirement of Solution: You are required to do this ab initio (bare-bones from scratch). This means, your solution cannot use any library methods in Java except the ones listed below (or equivalent library functions in C++). String.split() and other String operations can be used wherever required....
java programming write a program with arrays to ask the first name, last name, middle initial,...
java programming write a program with arrays to ask the first name, last name, middle initial, IDnumber and 3 test scores of 10 students. calculate the average of the 3 test scores. show the highest class average and the lowest class average. also show the average of the whole class. please use basic codes and arrays with loops the out put should look like this: sample output first name middle initial last name    ID    test score1 test score2...
You are to modify your payroll program from the last assignment to take the new copy...
You are to modify your payroll program from the last assignment to take the new copy of the payroll file called DeweyCheatemAndHow.txt which has the fields separated by a comma to use as input to your program and produce a file that lists all the salaried employee and their gross pay, then each hourly employee and their gross pay and finally each piece rate employee and their gross pay . You are to process all the entries provided in the...
Modify this program so that it takes in input from a TEXT FILE and outputs the...
Modify this program so that it takes in input from a TEXT FILE and outputs the results in a seperate OUTPUT FILE. (C programming)! Program works just need to modify it to take in input from a text file and output the results in an output file. ________________________________________________________________________________________________ #include <stdio.h> #include <string.h> // Maximum string size #define MAX_SIZE 1000 int countOccurrences(char * str, char * toSearch); int main() { char str[MAX_SIZE]; char toSearch[MAX_SIZE]; char ch; int count,len,a[26]={0},p[MAX_SIZE]={0},temp; int i,j; //Take...
Write Java program Lab52.java which reads in a line of text from the user. The text...
Write Java program Lab52.java which reads in a line of text from the user. The text should be passed into the method: public static String[] divideText(String input) The "divideText" method returns an array of 2 Strings, one with the even number characters in the original string and one with the odd number characters from the original string. The program should then print out the returned strings.
Program in Java using Inheritence The purpose of this assignment is to practice OOP programming covering...
Program in Java using Inheritence The purpose of this assignment is to practice OOP programming covering Inheritance. Core Level Requirements (up to 6 marks) The scenario for this assignment is to design an online shopping system for a local supermarket (e.g., Europa Foods Supermarket or Wang Long Oriental Supermarket). The assignment is mostly concentrated on the product registration system. Design and draw a UML diagram, and write the code for the following classes: The first product category is a fresh...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT