Write a java program that reads a text file containing integ
Write a java program that reads a text file containing integers, determines the average, and then outputs to a file every number in the input file greater than the average. Write to an output file named C13h1.txt.
Also, write another java program that reads a text file containing integers and displays the integer in reverse order.
Solution
Question 1:
ReadFileTest.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadFileTest {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print(\"Enter the file name: \");
String fileName = scan.next();
File file = new File(fileName);
if(file.exists()){
Scanner fileInput = new Scanner(file);
ArrayList<Integer> list = new ArrayList<Integer>();
while(fileInput.hasNextInt()){
list.add(fileInput.nextInt());
}
int sum = 0;
for(int n: list){
sum = sum + n;
}
double average = sum/(double)list.size();
PrintStream ps = new PrintStream(\"D:\\\\C13h1.txt\");
for(int n: list){
if(average < n){
ps.println(n);
}
}
ps.flush();
ps.close();
System.out.println(\"File has been created\");
}
else{
System.out.println(\"File does not exist\");
}
}
}
Output:
Enter the file name: D:\\\ ums.txt
File has been created
nums.txt
1 2 3 4 5 6 7 8 9 10
C13h1.txt
6
7
8
9
10
Question 2:
ReadFileAndDisplayReverse.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadFileAndDisplayReverse {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.print(\"Enter the file name: \");
String fileName = scan.next();
File file = new File(fileName);
if(file.exists()){
Scanner fileInput = new Scanner(file);
ArrayList<Integer> list = new ArrayList<Integer>();
while(fileInput.hasNextInt()){
list.add(fileInput.nextInt());
}
System.out.println(\"Numbers in reverse order: \");
for(int i=list.size()-1; i>=0; i--){
System.out.println(list.get(i));
}
}
else{
System.out.println(\"File does not exist\");
}
}
}
Output:
Enter the file name: D:\\\ ums.txt
Numbers in reverse order:
10
9
8
7
6
5
4
3
2
1

