In: Computer Science
File IO Java question
• Ask the user to specify the file name to open for reading
• Get the number of data M (M<= N) he wants to read from file
• Read M numbers from the file and store them in an array
• Compute the average and display the numbers and average.
Note: Could you plz go through this code and let me
know if u need any changes in this.Thank You
_________________
// fileDataNums.txt
23
34
45
56
67
76
65
54
43
32
21
78
89
90
9
8
76
44
55
67
77
88
_________________________
// ReadFilenos.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFilenos {
public static void main(String[] args) throws
FileNotFoundException {
int m,n=0;
double sum=0;
/*
* Creating an Scanner class object
which is used to get the inputs
* entered by the user
*/
Scanner sc = new
Scanner(System.in);
System.out.print("Enter m:");
m=sc.nextInt();
Scanner fileOpen = new Scanner(new
File("fileDataNums.txt"));
while(fileOpen.hasNext())
{
fileOpen.nextDouble();
n++;
}
fileOpen.close();
if(m<=n)
{
double nos[]=new double[m];
fileOpen=new Scanner(new
File("fileDataNums.txt"));
for(int i=0;i<m;i++)
{
nos[i]=fileOpen.nextDouble();
sum+=nos[i];
}
fileOpen.close();
System.out.println("Displaying the nos :");
for(int i=0;i<m;i++)
{
System.out.print(nos[i]+" ");
}
System.out.println("\nAverage :"+(sum/m));
}
else
{
System.out.println("** Invalid input **");
}
}
}
___________________________
Output:
Enter m:10
Displaying the nos :
23.0 34.0 45.0 56.0 67.0 76.0 65.0 54.0 43.0 32.0
Average :49.5
_______________Could you plz rate me well.Thank
You