So I need emergency help in writing a program that does a few simple things. I have a file that is composed of positive, negative and zero integers. Each integer has its own line and I'd say there's about 100 lines. I need help writing a program that will

1. Read the file and create and array from the data
2. Use that array to calculate the mode of the integers (the most frequently used integer)
3. Display the output back to the user.

Below I posted my current code using the hint that was given. Any help is appreciated. Thanks


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Lab0 { public static void main(String[] args) throws FileNotFoundException { String fileName = mode.txt";
File in = new File(fileName);
int frequency = countValues(in, 9);
System.out.println("\"9\" Count: " + frequency);
static int countValues(File inFile, int value) throws FileNotFoundException {
int freq = 0;
Scanner fileScanner = new Scanner(inFile);
while (fileScanner.hasNextInt()) {
int input = fileScanner.nextInt();
if (input == value) {
freq++; }
return freq;

To my knowledge, this code tracks the occurrence of a single value. Thus I need to come up with an array that reads all digits in the file and tracks their occurrence, then returns the most frequent value. Hopefully this helps

Edited by Ezzaral: Added code tags. Please use them to format any code that you post. Indenting would be helpful as well.

6 Years
Discussion Span
Last Post by Nox_1031

Ok first things first... please use code tags. This isn't too bad to read since it is so short but it's still messy.

As far as the logic is concerned, you could go a lot of ways with this. You could use a Map and link the values to the number of occurrences that way. You could also create your own "Number Tracking" class to keep track of the value and how many times you have encountered it.


Yeah I cross posted on another forum lol. Just trying to find an approach I'm most familiar with. I'll give the number tracking idea a run and see what happens. If not I'll just follow the long tedious way of doing it. Thanks for the help, appreciate the ideas.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.