Question

What to submit: your answers to exercises 2. Write a Java program to perform the following...

What to submit: your answers to exercises 2.

  1. Write a Java program to perform the following tasks:

The program should ask the user for the name of an input file and the name of an output file. It should then open the input file as a text file (if the input file does not exist it should throw an exception) and read the contents line by line. It should also open the output file as a text file and write to it the lines in the input file, prefixed by line numbers starting at 1.

So if an input file named “fred.txt” contains:

Hello,

I am Fred.

I am enrolled in ICT167.

Bye

and the user enters “fred.txt” and “fredNum.txt”, then after running the program “fredNum.txt” will contain something like:

1 Hello,

2

3 I am Fred.

4 I am enrolled in ICT167.

5

6 Bye

Finally, the program should display on the screen your name, the name of the output file, followed by a count of the total number of lines, the total number of words, and the total number of characters in the input file.

For the above input file, the following will be displayed to the screen:

My name = Joe Bloggs

Name of Output file = fredNum.txt Total number of lines in fred.txt = 6 Total number of words in fred.txt = 10

Total number of characters in fred.txt = 43

  1. Write a Java program to perform the following tasks:

The program should ask the user for the name of an input file (scores.txt). The input file should contain 10 records. Each record in the input file should consist of a name and score between 0 and 100 (inclusive). Eg: fred 95

The program should open the input file as a text file (if the input file does not exist it should throw an exception) and read the contents line by line.

Store each record in an array of a user-defined Score class. The Score class can be kept very simple with 2 instance variables, a default constructor, get and set methods for the instance variables.

Now process the array of Score class objects to determine:

  • The average of all scores
  • The largest score
  • The smallest score

Now output the above stats and all records to the file output.csv. The first line written to this file should consist of the number of records, the average score, the largest score and the smallest score; these values should be comma separated. Finally, the contents of the array of Score objects should be written to output.csv starting from the second line (the first line being taken by the above stats). The format to output the array contents is the same as the input file, with the exception that the fields should be comma separated instead of space separate

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code

First task


import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;


public class Main {

public static void main(String[] args) {
int lineCount=0;
int wordCount=0;
int charCount=0;
String inputFile,outputFile;
Scanner input,scnr;
scnr=new Scanner(System.in);
System.out.println("Please enter input file name.");
inputFile=scnr.next();
System.out.println("Please enter output file name.");
outputFile=scnr.next();
  
try
{
input=new Scanner(new File(inputFile));
FileWriter myWriter = new FileWriter(outputFile);
String line;
while(input.hasNext())
{
lineCount++;
line=input.nextLine();
myWriter.write(lineCount+" "+line+"\n");
charCount+=line.length();
if(!line.isEmpty())
{
String words[]=line.split(" ");
wordCount+=words.length;
}
}
myWriter.close();
input.close();
System.out.println("My name = Joe Bloggs");
System.out.println("Name of Output file = "+outputFile+"\nTotal number of lines in "+inputFile+" = "+lineCount+"\nTotal number of words in fred.txt = "+wordCount);
System.out.println("Total number of characters in "+inputFile+" = "+charCount);
}
catch(Exception e)
{
System.out.println(inputFile+" file not found. Please try again.");
}
}
  
}

output

Output > Debugger Console Read file and the write to file with line number (run) x run: Please enter input file name. fred.tx

fredNum.txt file- х fred Num - Notepad File Edit Format View Help Hello, 2 3 I am Fred. 4 I am enrolled in ICT167. 5 6 Bye Ln 1, Col 1 100% U

Second task

Code


import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

class Score
{
private String name;
private int score;

public Score(String name, int score) {
this.name = name;
this.score = score;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getScore() {
return score;
}

public void setScore(int score) {
this.score = score;
}
  

}
public class ScoreTest {

public static void main(String[] args) {
String inputFile,name;;
int score,i=0,maxScore,minScore;
double sum=0,avg;
Score scoreArray[]=new Score[10];
final String outputFile="output.csv";
Scanner scnr,input;
scnr=new Scanner(System.in);
System.out.print("Enter input file name: ");
inputFile=scnr.next();
try
{
input=new Scanner(new File(inputFile));
while(input.hasNext())
{
name=input.next();
score=input.nextInt();
scoreArray[i]=new Score(name, score);
i++;
}
maxScore=minScore=scoreArray[0].getScore();
for(int j=0;j<i;j++)
{
sum+=scoreArray[j].getScore();

if(maxScore<scoreArray[j].getScore())
maxScore=scoreArray[j].getScore();

if(minScore>scoreArray[j].getScore())
minScore=scoreArray[j].getScore();
}
avg=sum/i;
FileWriter myWriter = new FileWriter(outputFile);
myWriter.write(i+","+avg+","+maxScore+","+minScore+"\n");
for(int j=0;j<i;j++)
myWriter.write(scoreArray[j].getName()+","+scoreArray[j].getScore()+"\n");
myWriter.close();
input.close();
}
catch(Exception e)
{
System.out.println(inputFile+" was not found. Please try again.");
}
}
  
}

scores.txt

- х scores - Notepad File Edit Format View Help Fred 96 Jack 85 Jill 78 Pintu 80 Bob 96 Alice 78 John 70 Abdul 90 Ali 85 Bara

output on console

Output > Debugger Console * Score class with read from file (run) x D Enter input file name: scores.txt BUILD SUCCESSFUL (tot

output.csv

output.csv X 1 10,83.8,96,70 2 Fred, 96 3 Jack, 85 4 Jill,78 5 Pintu, 80 6 Bob,96 7 Alice, 78 8 John, 70 Abdul, 90 10 Ali, 85

If you have any query regarding the code please ask me in the comment i am here for help you. Please do not direct thumbs down just ask if you have any query. And if you like my work then please appreciates with up vote. Thank You.

Add a comment
Know the answer?
Add Answer to:
What to submit: your answers to exercises 2. Write a Java program to perform the following...
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
  • CIS 22A C++ Project Exam Statistics Here is what your program will do: first it welcomes...

    CIS 22A C++ Project Exam Statistics Here is what your program will do: first it welcomes the user and displays the purpose of the program. It then prompts the user to enter the name of an input file (such as scores.txt). Assume the file contains the scores of the final exams; each score is preceded by a 5 characters student id. Create the input file: copy and paste the following data into a new text file named scores.txt DH232 89...

  • Lab Assignment 4B Modify your program in Lab Assignment 4A to throw an exception if the...

    Lab Assignment 4B Modify your program in Lab Assignment 4A to throw an exception if the file does not exist. An error message should result.   Use the same file name in your program as 4A, however, use the new input file in 4B assignment dropbox. Lab 4A: Write a program that reads a file (provided as attachment to this assignment) and writes the file to a different file with line numbers inserted at the beginning of each line. Test with...

  • Program in C++! Thank you in advance! Write a menu based program implementing the following functions: (1) Write a funct...

    Program in C++! Thank you in advance! Write a menu based program implementing the following functions: (1) Write a function that prompts the user for the name of a file to output as a text file that will hold a two dimensional array of the long double data type. Have the user specify the number of rows and the number of columns for the two dimensional array. Have the user enter the values for each row and column element in...

  • Write the program in C The following statistics for cities of the Vege country are stored...

    Write the program in C The following statistics for cities of the Vege country are stored in a file: Name: a string of characters less than 15 characters long. Population: an integer value. Area: square miles of type double Write a program that: asks and gets the name of the input file from the user. Read the contents of the file into an array length 10 of structures -ask the user for the name of a city (less than 15...

  • Write a python program that prompts the user for the names of two text files and...

    Write a python program that prompts the user for the names of two text files and compare the contents of the two files to see if they are the same. If they are, the scripts should simply output “Yes”. If they are not, the program should output “No”, followed by the first lines of each file that differ from each other. The input loop should read and compare lines from each file. The loop should break as soon as a...

  • 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...

  • Python 3.7 Coding assignment This Program should first tell users that this is a word analysis...

    Python 3.7 Coding assignment This Program should first tell users that this is a word analysis software. For any user-given text file, the program will read, analyze, and write each word with the line numbers where the word is found in an output file. A word may appear in multiple lines. A word shows more than once at a line, the line number will be only recorded one time. Ask a user to enter the name of a text file....

  • please answer correctly and follow the code structure given [JavaFX/ Exception handing and text I/O] 1....

    please answer correctly and follow the code structure given [JavaFX/ Exception handing and text I/O] 1. Write a program for the following. NOTE that some of these steps are not dependent on each other. Using methods is mandatory. Make sure to use methods where it makes sense. a. Ask the user for a series of integers entered from the keyboard. Use a sentinel value such as 999 to end the input process. If the entered values are not integers, throw...

  • Write a complete C++ program that reads students names and their test scores from an input...

    Write a complete C++ program that reads students names and their test scores from an input text file. The program should output each student’s name followed by the test scores and the relevant grade in an output text file. It should also find and display on screen the highest/lowest test score and the name of the students having the highest/lowest test score, average and variance of all test scores. Student data obtained from the input text file should be stored...

  • Programming Exercise 4.9 Write a script named numberlines.py. This script creates a program listing from a...

    Programming Exercise 4.9 Write a script named numberlines.py. This script creates a program listing from a source program. This script should: Prompt the user for the names of two files. The input filename could be the name of the script itself, but be careful to use a different output filename! The script copies the lines of text from the input file to the output file, numbering each line as it goes. The line numbers should be right-justified in 4 columns,...

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