Write a program that • creates three text files: grade1.txt, grade2.txt, grade3.
ID: 3773821 • Letter: W
Question
Write a program that
• creates three text files: grade1.txt, grade2.txt, grade3.txt
o Each contains 5 students’ names (first name, last name) and grades (integers) that are obtained from the keyboard input.
• combine all three files into one text file: allgrades.txt
o It contains all 15 students' names and grades from the 3 text file.
o It also contains letter grades for each student
If grade < 60, it adds letter grade "F"
If 60 <= grade <70, it adds letter grade "D".
If 70 <= grade < 80, it adds letter grade "C".
If 80 <= grade < 90, it adds letter grade "B".
If 90 <= grade, it adds letter grade "A".
• displays the contents of text file allgrade.txt on the console
Using Standard java code and explain the code using comments.
Explanation / Answer
In the inner for loop we can create ArrayList<Integer> whose unique object will be created dynamically, to store the grade number from user(keyboard).
While writing the text in allgrades.txt we can use the ArrayList we created to print the grade values by comparing grade numbers.
package com.chegg.textfiles;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class TextFile {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// PrintWriter pw=new PrintWriter("C:/Users/ramakgad/Desktop/Chegg/textfiles/allgrades.txt");
for(int i=1;i<=3;i++){
String path="C:/Users/ramakgad/Desktop/Chegg/textfiles/grade"+i+".txt";
PrintWriter writer = new PrintWriter(path, "UTF-8");
System.out.println("File Number: "+i);
System.out.println("Enter all the 5 students names and their respective grades");
for(int j=1;j<=5;j++){
Scanner scn=new Scanner(System.in);
System.out.println("Student number: "+j);
System.out.print("First Name: ");
String first_name=scn.nextLine();
writer.print(first_name+" ");
System.out.print("Last Name: ");
String last_name=scn.nextLine();
writer.print(last_name+" ");
System.out.print("Grade: ");
int grade=scn.nextInt();
writer.print(grade+" ");
System.out.println(" ");
}
writer.close();
}
String path="C:/Users/ramakgad/Desktop/Chegg/textfiles/allgrades.txt";
File file=new File(path);
file.createNewFile();
for(int k=1;k<=3;k++){
FileReader reader=new FileReader("C:/Users/ramakgad/Desktop/Chegg/textfiles/grade"+k+".txt");
BufferedReader br=new BufferedReader(reader);
String temp;
PrintWriter pw1 = new PrintWriter(new FileWriter(file, true));
while((temp=br.readLine())!=null){
//String temp=br.readLine();
pw1.print(temp);
System.out.println(temp);
pw1.print(" ");
}
pw1.close();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.