In: Computer Science
Create a class called clsTextProcessor.java. Your program should deliver the following:
ClsTextProcessor.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ClsTextProcessor {
public static void main(String[] args) {
Scanner scan = new
Scanner(System.in);
System.out.println("Enter file
name:");
String fileName =
scan.next();
// Reading file name
File file = new
File(fileName);
// Loop to enter valid file name
and location
while (!file.exists()) {
System.out
.println("Invalid file and
location. Enter valid file name:");
fileName =
scan.next();
file = new
File(fileName);
}
try {
// number of
values
int count =
0;
// max, min, sum
variables initialized with 0
int max = 0, min
= 0, sum = 0;
Scanner fileRead
= new Scanner(file);
// reading each
value from file and keeping in num variable
while
(fileRead.hasNextInt()) {
int num = fileRead.nextInt();
if (count == 0) {
// file value from file
assigned to min, max
max = min = num;
} else {
if (min > num) {
min =
num;
}
if (max < num) {
max =
num;
}
}
// Adding each value
sum += num;
// count increased for each value
count++;
}
// calculating
average value
double avg = sum
/ (double) count;
System.out.println("Minimum value: " + min);
System.out.println("Maximum value: " + max);
System.out.println("The average value of all number in the text:
"
+ avg);
} catch (FileNotFoundException e)
{
System.out.println("File is not found");
}
}
}
Output:
Enter file name::
D://numbers111.txt
Invalid file and location. Enter valid file name:
D://numbers.txt
Minimum value: 1
Maximum value: 10
The average value of all number in the text: 5.5
numbers.txt:
1 2 3 4 5 6 7 8 9 10