1,105,399 Community Members

Program to read file and calculate array

Member Avatar
Nox_1031
Newbie Poster
2 posts since Sep 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
hag++
Posting Whiz in Training
239 posts since Jan 2010
Reputation Points: 24 [?]
Q&As Helped to Solve: 36 [?]
Skill Endorsements: 0 [?]
 
0
 

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.

Member Avatar
NormR1
Posting Sage
7,723 posts since Jun 2010
Reputation Points: 563 [?]
Q&As Helped to Solve: 793 [?]
Skill Endorsements: 16 [?]
Team Colleague
 
0
 
Member Avatar
Nox_1031
Newbie Poster
2 posts since Sep 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article