Find the most frequent value in an array of double in Java (without hashmaps or sorting) -
write full java program following:
creates array of 100 double.
reads in unknown number of doubles file named values.txt .
there @ least 2 distinct values, , no more 100 distinct values in file. values in unsorted order. values no smaller 0, , no larger 99.
outputs occurring value in file.
outputs least occurring value in file. value must occur @ least once in order output.
outputs average of array values.
you must create , use separate methods each of items #2-5.
this have far. cannot life of me figure out how right:
import java.util.*; import java.io.*; public class arrayprogram2 { static scanner console = new scanner(system.in); static final int array_size = 100; static int numofelements = 0; public static void main(string[] args) throws filenotfoundexception { scanner infile = new scanner(new filereader("values.txt")); double[] arr1 = new double[array_size]; while (infile.hasnext()) { arr1[numofelements] = infile.nextdouble(); numofelements++; } system.out.println("there " + numofelements + " values."); system.out.printf("the average of values %.2f%n", avgarray(arr1)); system.out.println("the sum " + sumarray(arr1)); infile.close(); } //end main //method calculate sum public static double sumarray(double[] list) { double sum = 0; (int index = 0; index < numofelements; index++) { sum = sum + list[index]; } return sum; } //method calculate average public static double avgarray(double[] list) { double sum = 0; double average = 0; (int index = 0; index < numofelements; index++) { sum = sum + list[index]; } average = sum / numofelements; return average; } } //end program
notice required make array of double though not necessary.
it's possible find most-occurring value without sorting this:
static int countoccurrences(double[] list, double targetvalue) { int count = 0; (int = 0; < list.length; i++) { if (list[i] == targetvalue) count++; } } static double getmostfrequentvalue(double[] list) { int mostfrequentcount = 0; double mostfrequentvalue = 0; (int = 0; < list.length; i++) { double value = list[i]; int count = countoccurrences(list, value); if (count > mostfrequentcount) { mostfrequentcount = count; mostfrequentvalue = value; } } return mostfrequentvalue; }