Answer this question using Java only.... write a Java program to read in all of
ID: 648945 • Letter: A
Question
Answer this question using Java only....
write a Java program to read in all of the numbers in the file into an array. Then find the median of the numbers and print it out to the console. The median should be of type double. The median of a list of even numbers is the average of the middle two numbers, so for this example assume the median is ((NUMBER_2+NUMBER_3) / 2). find the average of the numbers in the array.
please fix my code and finish rest of it. also leave comments where you read the numbers from file into array. and please keep it simple. btw there 4 single digit numbers in my numbers.txt file
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
public class FileArray{
Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws IOException{
File myFile = new File("numbers.txt");
Scanner inputFile = new Scanner(myFile);
int[] numberFile = new int[4];
int i = 0;
while (inputFile.hasNext())
{
int numFile = inputFile.nextInt();
System.out.println(numFile);
}
inputFile.close();
}
}
Explanation / Answer
/**
* java program that reads a text file numbers.txt
* that contains 4 numbers into an array of size 4.
* Then finds median and average
* of the numbers and print to console
* */
//FileArray.java
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class FileArray
{
Scanner scnr = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
//createa File class object
File myFile = new File("numbers.txt");
//Create an instance of Scanner class object with File object
Scanner inputFile = new Scanner(myFile);
int[] numberFile = new int[4];
int i = 0;
//delcare variables
double median;
double sum=0;
int middle;
//check if file contains integers
while (inputFile.hasNextInt())
{
//read integer from Scanner object inputFile
//and store in a array numberFile
numberFile[i] = inputFile.nextInt();
sum+=numberFile[i];
//increment i by one
i++;
}
//find middle position of the array
middle=(numberFile.length)/2;
//find median of two elements at indexes middle-1 and middle
median=(numberFile[middle-1]+numberFile[middle])/2.0;
//print median
System.out.println("Median : "+median);
//print average
System.out.println("Average : "+sum/numberFile.length);
//close inputFile object
inputFile.close();
}//end of the main
}//end of the class
-------------------------------------------------
Sample output:
sample text file
numbers.txt
1 2 3 4
output:
Median : 2.5
Average : 2.5
Hope this helps you
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.