First, I have an input file with 11 (or less) lines of numbers.
Part of my assignment is to find the mode ( number that appears the most ) WITHOUT using arrays. I have tried to use for loops or if loops after finding the amount of lines in my input file. I know it sounds stupid to do this without arrays, but I am not allowed to use arrays in this assignment.
Since I made variables ( earnedGrade1, earnedGrade2, earnedGrade3, etc. ) for each number that is pulled from the input file, I'm not sure how to compare the numbers without using consecutive if statements ( as shown in example below ).
//Assume count has been declared and initialized to 0
//Assume earnedGrade1/2/3 has been intialized with the numbers
pulled from input file
if(earnedGrade1 == earnedGrade2)
{
count++;
}
if(earnedGrade1 == earnedGrade3)
{
count++;
}
The above example doesn't seem to be a very good way to find the mode, since I would have to do around 11 if-statements for each and every earnedGrade variable.
If anyone has any suggestions, please do help.
Thank you for any help and please understand that I am new to programming.
One way to do this without an array is to write a helper method, something like this:
static int count(double gradeToCount, double grade1, ..., double gradeN) {
int count = 0;
if (gradeToCount == grade1)
count++;
if (gradeToCount == grade2)
count++;
// And so on...
return count;
}
It's just like if you were using a loop:
for (double grade : gradesArray)
if (gradeToCount == grade)
count++;
Except the loop is unrolled, and you check each grade and increment the count yourself.
Once you can count the occurrences of each grade, then you have to write another unrolled loop where you find the grade which has the maximum count.
Writing a helper method means that you only have to write out 2N comparisons by hand instead of N2 comparisons.
I don't really know what you are supposed to learn from having to do it this way, except for why arrays are necessary I guess.
I was thinking about it again, and another way to do this would be to just repeatedly read the file using Scanner. Something like this:
Scanner in1 = new Scanner(fileOrPath);
while (in1.hasNextDouble()) {
double gradeToCount = in1.nextDouble();
Scanner in2 = new Scanner(fileOrPath);
while (in2.hasNextDouble()) {
double grade = in2.nextDouble();
if (grade == gradeToCount)
count++;
}
}
This is pretty awful too, but it could be better than writing the comparisons by hand, I guess. I think Poosh's answer is suggesting something similar to this.
Probably not the most efficient, but here's an idea from what you mentioned you've covered in the course so far: read the input file into a String. Then write methods that let you do things to the String that you can do with an array, like get the count of items, and get the item at a certain index. Then you could do some loops using those methods.
One way might be to get the first number in the String, count how many times you find it, then store that number and how many times it appears in the String in variables. Then go to the second number in the String, do the same thing, and reset those variables if the number appears more times than the previous number. Otherwise leave the variables alone. Once you get to the last item in the String, you'll have your mode.
Another downside besides the inefficiency is that this would only find a single mode. You could overcome this by using another String to "play the role of an array" using methods.
I believe the simplest (yet most laborious) solution here would be to use several if-else statements like you suggest. I think your instructor wants to show you that using several if-else statements in programming is inefficient and that he is using this question in order to transition into another concept. Either that, or the instructor is simply making your assignment busy work by introducing this requirement.
Since you are in an introductory class you probably have not been taught about more advanced data structures like ArrayLists yet and so unless you are allowed to use such structures for this assignment, you will have no other option but to make a huge if-else section in your code.
I have an idea, I know it's a pain because the program need to loop through the file many times, but however, it may be helpful as it doesn't use any array nor Collection (Explanation in Comments):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* The "mode" is the value that occurs most often
*/
public class ModeWithoutArray {
public static void main(String[] args) {
int count =0, lines = 0;
double mode =0;
File file = new File("C:\\Users\\Yahya\\Desktop\\grades.txt"); // for example
try {
Scanner read = new Scanner(file);
// count how many lines/grades the file contains
while(read.hasNextLine()){
read.nextLine();
lines++;
}
// now compare every grade with the others (line by line) specified by the index "i"
for(int i=0; i<lines; i++){
int result = count(i, file); // count how many time it's repeated
if(result>count){ // if it's bigger than the current count
count=result; // accept it
mode = findGrade(file, i); //then find the actual grade at that line
}
}
read.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
System.exit(0);
}
if(count>1){
System.out.println("The Mode is: " + mode + ", Repeated " + count + " times" );
}
else{
System.out.println("No Mode Found" );
}
}
// this method to count the repetition of a grade at particular line
private static int count(int atLine, File file){
double gardeToCount = 0;
int count=0;
try {
Scanner read = new Scanner(file);
// find the grade at that line
gardeToCount = findGrade(file, atLine);
// then compare it with other grades
while(read.hasNextLine()){
if(gardeToCount==Double.parseDouble(read.nextLine())){
count++;
}
}
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return count; // return the count
}
// this method to find the actual grade at a given line in the file
private static double findGrade(File file, int atLine){
int line =0;
try {
Scanner read = new Scanner(file);
while(read.hasNextLine()){
if(line==atLine){
return Double.parseDouble(read.nextLine());
}
read.nextLine();
line++;
}
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return 0;
}
}
Test
The File Content (grades.txt)
50
60
70
80
50
60
60
90
100
Output
The Mode is: 60.0, Repeated 3 times
UPDATE
Another approach, which is also more efficient, instead of reading the file many times [Also Added Validation To The File Content], you can do something like this (Explanation in Comments):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* The "mode" is the value that occurs most often
*/
public class ModeWithoutArray {
static int count =0, lines = 0;
static double mode =0;
public static void main(String[] args) {
// the file that contains the grades (a grade at each line)
File file = new File("C:\\Users\\Yahya\\Desktop\\grades.txt");
// get all grades and convert them to a String separated by one space
String allGrades = collectGrades(file);
double gradeToComapre = 0;
int gradeRep = 0;
// compare every grade with the others and count its repetition
// every round change mode and count to the bigger values
for(int i=1; i<=lines; i++){
gradeToComapre = grade(allGrades, i);
for(int j=i; j<=lines; j++){
if(gradeToComapre==grade(allGrades, j)){
gradeRep++;
}
}
if(gradeRep>count){
count=gradeRep;
mode = gradeToComapre;
}
gradeRep = 0;
}
if(count>1){ // if there is a mode
System.out.println("The Mode is: " + mode + ", Repeated " + count + " times." );
}
else{
System.out.println("The Collection Has No Mode!" );
}
}
//////////////////////////////////////////////////////////////////////
/**
* This method to collect all Valid Grades
* from a given file and concatenate them to a String to be
* returned at the end
* #param file
*/
private static String collectGrades(File file){
String allGrades = "";
try {
Scanner read = new Scanner(file);
// read the file and accept ONLY valid grades
while(read.hasNextLine()){
String oneGrade = read.nextLine().trim();
if(!oneGrade.isEmpty() && isValidGrade(oneGrade)){
allGrades += oneGrade + " "; // one space between every grade
// increment the global variable lines
// to be used in the comparison loops
lines++;
}
}
read.close();
} catch (FileNotFoundException e) {
System.out.println("File Does Not Exists!");
System.exit(0);
}
return allGrades;
}
//////////////////////////////////////////////////////////////////////
/**
* This method to check if a given Grade is valid
* this will return true/false
* #param oneGrade
*/
private static boolean isValidGrade(String oneGrade){
try{ // try to parse it as a double value
// this will throw an exception if it's not a number!
double theGrade = Double.parseDouble(oneGrade);
if(theGrade>=0 && theGrade<=100){ // is it in the range?
return true;
}
}catch(NumberFormatException e){
// catch the exception if it's not a number
// and return false
return false;
}
// return false if it's <0 or >100
return false;
}
//////////////////////////////////////////////////////////////////////
/**
* This method to fetch a particular grade from the
* String that contains all grades
* #param allGrades
* #param index
*/
private static double grade(String allGrades, int index){
String oneGrade = "";
int count = 0;
for(char c : allGrades.toCharArray()){
if(!Character.isWhitespace(c)){
// if it's not a space, concatenate the char to oneGrade
oneGrade += c;
}
else{ // the space determines the end of grade
count++;
if(count==index){ // if it's the required grade
// return it as a double
return Double.parseDouble(oneGrade);
}
else{// if it's not the required grade
// restart concatenation
oneGrade = "";
}
}
}
// this will never be the case unless you
// ask for a grade out the range
// (e.g. there are 3 grades and you want the fourth!!)
return -1;
}
}
Test
The File Content (grades.txt)
50
60.5
66
75
32
95
50.5
75
60.5
80
60.5
78
Output:
The Mode is: 60.5, Repeated 3 times.
Related
I'm a beginner and I have tried a few different ways from the stuff that I have learned from other people's questions, but I think my problem with the following problem is that I can't figure out the logic of my code. If someone can suggest a solution with explaining the logic of the codes, I would greatly appreciate it.
I'm supposed to create a method in the format of method() that will prompt the user to enter a script that includes String, numbers, and doubles. The method should count the number of Strings, numbers, and doubles and prints out the list of the string, numbers and doubles. I have got the part that the method prints the list of the strings, numbers and doubles, but it seems I can't get the counter to count them. I have got this so far:
import java.util.Scanner;
public class Games {
private Scanner input;
public Games() {
input = new Scanner(System.in);
}
public void textParser() {
System.out.println("Enter a Script");
int intCount = 0;
int dblCount = 0;
int strCount = 0;
while(input.hasNext()) {
if(input.hasNextInt()) {
int num = input.nextInt();
System.out.println(num);
intCount++;
}else if(input.hasNextDouble()) {
double value = input.nextDouble();
System.out.println(value);
dblCount++;
}else {
String oneWord = input.next();
System.out.println(oneWord);
strCount++;
}
}
System.out.println("Number of integers: " + intCount);
System.out.println("Number of doubles: " + dblCount);
System.out.println("Number of strings: " + strCount);
}
public static void main(String[] args) {
Games demo = new Games();
demo.textParser();
}
}
Example of expected inputs and outputs:
Enter a Script
32 quick brown foxes jump over 65 lazy dogs and few doubles are 43.3
and 76.9
32
65
Number of integers: 2
43.3
76.9
Number of doubles: 2
quick
brown
foxes
jump
over
lazy
dogs
and
few
doubles
are
and
Number of strings: 12
Actual output:
32
65
43.3
76.9
quick
brown
foxes
jump
over
lazy
dogs
and
few
doubles
are
and
Near the beginning, you say while(scanner.hasNext(). This means, that all the code in the loop will be excecuted pretty much as long as the program runs.
You have put the statements that print the counters outside of the loop, and designed your code in a way, that you will never leave that loop.
So you need some kind of exit condition. Let's say, if one of the strings is exit, you exit the loop and print the counters:
while (input.hasNext()) {
if (input.hasNextInt()) {
// ...
} else if (input.hasNextDouble()) {
// ...
} else {
String oneWord = input.next();
System.out.println(oneWord);
strCount++;
if (oneWord.equals("exit")) {
input.close();
break;
}
}
}
or, if you don't want to have to put "exit" in there, do this:
int intCount = 0, doubleCount = 0, stringCount = 0;
while (input.hasNextLine()) {
String[] segments = input.nextLine().split(" ");
for (String segment : segments) {
System.out.println(segment);
try {
int asInt = Integer.parseInt(segment);
intCount++;
} catch (NumberFormatException e) {
try {
double asDouble = Double.parseDouble(segment);
doubleCount++;
} catch (NumberFormatException e2) {
stringCount++;
}
}
}
System.out.println("Number of integers: " + intCount);
System.out.println("Number of doubles: " + doubleCount);
System.out.println("Number of strings: " + stringCount);
}
The Scanner will continue to read until it finds an "end of file" condition.
As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix) or at the end of the file if you use < style redirection.
You need some kind of exit condition
if (oneWord.equals("exit")) {
input.close();
break;
}
Another approach after giving your input Ctrl+Z it will send EOF.
below is my code for a homework assignment where I need to read the contents of an external file and determine the number of words within it, number of 3-letter words, and percentage of total. I've got that part down just fine, but I also have to print the external file's contents prior to displaying the above information. Below is my current code:
public class Prog512h
{
public static void main( String[] args)
{
int countsOf3 = 0;
int countWords = 0;
DecimalFormat round = new DecimalFormat("##.00"); // will round final value to two decimal places
Scanner poem = null;
try
{
poem = new Scanner (new File("prog512h.dat.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!"); // returns error if file is not found
System.exit (0);
}
while (poem.hasNext())
{
String s = poem.nextLine();
String[] words = s.split(" ");
countWords += words.length;
for (int i = 0; i < words.length; i++)
{
countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words
}
}
while(poem.hasNext())
{
System.out.println(poem.nextLine());
}
System.out.println();
System.out.println("Number of words: " + countWords);
System.out.println("Number of 3-letter words: " + countsOf3);
System.out.println("Percentage of total: " + round.format((double)((double)countsOf3 / (double)countWords) * 100.0)); // converts value to double and calculates percentage by dividing from total number of words
}
}
The statement
while(poem.hasNext())
{
System.out.println(poem.nextLine());
}
is supposed to print the external file's contents. However, it doesn't. When I try moving it before my prior while loop, it prints, but screws up my printed values for the # of words, 3-letter words, percentage, etc. I'm not really sure what the issue is here. Could someone provide some assistance?
Thank you in advance.
Your scanner is trying to reread the file but it is at the bottom so there are no more lines to read. You have two options:
Option 1
Create a new Scanner object for the same file (to start at the beginning again) and then call your while loop on that file (works, but not a great design).
Scanner poem2 = null;
try
{
poem2 = new Scanner (new File("prog512h.dat.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!"); // returns error if file is not found
System.exit (0);
}
while(poem2.hasNext())
{
System.out.println(poem2.nextLine());
}
Option 2
A better option would be to display each line as you read it in. This can be accomplished by adding an extra line to the already existent while loop:
while (poem.hasNext())
{
String s = poem.nextLine();
System.out.println(s); // <<< Display each line as you process it
String[] words = s.split(" ");
countWords += words.length;
for (int i = 0; i < words.length; i++)
{
countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words
}
}
This only requires one Scanner object and only requires one read-through of the file which is much more efficient.
My output for the number of words and char keeps giving me zero. If anyone could help me find the
error in my code that would be great. The code enclosed by the stars is the code given by our teacher
and we are required to put this in our program.
Thank you!
** Our teacher told us not to use the buffered method. Also if I changes the lineNum method would it still override other methods?
Part of the assignment is to use at least two methods in our program****
** I edited my code based on everyones advice** It is now printing the correct numbers! How can I implement my two methods within this? A suggestion was that I use the for loop for the wordCount method.
I also need help with counting number of paragraphs
A good starting point?
import java.util.*;
import java.io.*;
public class WordStats1 {
public static void main(String[] args) {
try {
Scanner input = new Scanner(new FileReader("data.txt"));
//int totalLines = lineNum(input);
//int wordCount = wordCount(input);
//int countChar = countChar(input);
PrintWriter output = new PrintWriter(new FileOutputStream(
"newfile.txt"));
int lineNum = 0;
int wordCount = 1;
int charCount = 0;
while (input.hasNextLine()) {
String line;
line = input.nextLine();
//output.println(lineNum + ": " + line);
lineNum++;
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordCount ++;
}
}
charCount += (line.length());
}
System.out.println(lineNum);
System.out.println(wordCount);
System.out.println(charCount);
input.close();
output.close();
System.out.print("File written.");
}
catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
}
The issue is that, once you've called lineNum(), you are at the end of the file. When wordCount() and countChar() call hasNextLine(), this returns false and the functions return zero.
For some ideas on how to rewind a Scanner, see Java Scanner "rewind".
You need to do your linecount, word count and character count all inside a single loop. By having 3 functions, the very first function call to lineNum iterates over your scanner object, then the other two function calls return 0 because the scanner object has already read the file and as it is at the end of the file there is nothing left to read.
I would suggest you edit your teachers code, in particular the while loop. Remove the 3 functions and the corresponding function calls and have the program do all of your counting inside the loop inside the main() function.
int lineCount = 0;
int wordCount = 0;
int charCount = 0;
while (input.hasNextLine()) {
// read a line from the input file
String line = input.nextLine();
// increment line count
lineCount++;
// split line into words and increment word count
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordCount ++;
}
}
// increment char count
charCount += (line.length());
}
EDIT
Given that you have said you need to use 2 methods, heres what I suggest:
Move the word counting code above (the for loop) into a function of its own, it takes a String argument (the current line) and returns an integer. You can keep calling this from inside the loop.
wordCount += countWordsInString(line);
The lineNum() method essentially 'consumes' the file, so input.hasNextLine() always returns false in the wordCount() and countChar() methods, hence you get zero in those two cases.
Either combine all three methods in one uber-counter and process the file once, or load the file into some temporary variable such as a string and pass that into the three methods.
This assignment is comprised of creating a program to read up to (but not more) 25 test grades, then report the number of grades entered; and compute the arithmetic mean (average) and standard deviation of the grades. I don't understand how to use the get methods I have created so I can implement it in my program. Here is my code so far
package my.meancalculator;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
public class MeanCalcUI extends javax.swing.JFrame {
private double average;
private double stdDeviation;
public double[] gradeArray;
public int numElem;
public double sum;
public int i;
public double numGrades;
public MeanCalcUI() {
initComponents();
}
public double getAverage(double[] gradeArray, int numElem) {
double sum = 0;
for (int i = 0; i < numElem; i++) {
sum = sum + gradeArray[i];
}
return (sum / numElem);
}
public double getStdDev(double[] gradeArray, int numElem, double average) {
double sum = 0;
for (int i = 0; i < numElem; i++) {
sum = sum + Math.pow((gradeArray[i] - average), 2);
}
return Math.sqrt(sum / numElem);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void btnEnterGradesActionPerformed(java.awt.event.ActionEvent evt) {
gradeArray = new double[25];
JFrame frame = new JFrame();
boolean enterGrades = true;
while (enterGrades) {
try {
String gradeInput = JOptionPane.showInputDialog(frame,
"Enter Grade",
"Enter Grade",
JOptionPane.PLAIN_MESSAGE);
if ((gradeInput != null) && (gradeInput.length() > 0)) {
gradeArray[i] = Double.parseDouble(gradeInput);
average = getAverage;
numElem = numGrades + 1; //right here I know it doesn't work but i have no idea on how to make it the total of the grades entered. numElem is what the sum is getting divided by to find the average
txtNumGrades.setText((numGrades) + "");
txtMean.setText(average);
txtStdDeviation.setText(stdDeviation);
} else {
enterGrades = false;
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"Your input must be numeric!",
"Bad Data!",
JOptionPane.ERROR_MESSAGE);
}
}
}
Also, I don't know how I can make another catch block in case the user enters more than 25 grades. Here is my program guidelines from my teacher so you can have a better understanding on what it looks like and what is exactly being asked. http://homepages.uc.edu/~thomam/OOProg_1/assignment5.html
Can you guys help me out?
EDIT: Another question. How can I make the variable numElem work? I don't know how I can make that equal to the sum of all the grades entered.
The main problem you are asking about is trying to access those other methods you wrote, like getAverage(). You need to always pass those methods parameters; a name without parentheses after it is treated as just a variable, but through the magic of syntax the moment you put some parentheses with parameters, it becomes a method call: getAverage(gradeArray, numberOfGradesInput).
That said, there are faster ways to do most of what you're working on.
////////// CLASS FIELDS //////////
private double[] gradeArray = new double[25];
private int numberOfGradesInput = 0;
// You do not need any other fields! None! This is all you need to remember!
////////// BUTTON PRESSED //////////
if (numberOfGradesInput == 25) {
// We've already finished entering the max # of grades
JOptionPane.showMessageDialog(frame,
"You've already entered the maximum of 25 grades.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
do {
String gradeInput = JOptionPane.showInputDialog(frame,
"Enter Grade",
"Enter Grade",
JOptionPane.PLAIN_MESSAGE);
// When we receive empty/null input, we're done entering grades
if (gradeInput == null || gradeInput.length() == 0) break;
double gradeValue = 0d; // Set to avoid 'may be unset' compiler error
try {
gradeValue = Double.parseDouble(gradeInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"Your input must be numeric!",
"Bad Data!",
JOptionPane.ERROR_MESSAGE);
continue; // start over again
}
// Put the grade into the array and update the number of grades entered
gradeArray[numberOfGradesInput] = gradeValue;
numberOfGradesInput++;
// Add to the grade total
txtNumGrades.setText(Integer.toString(numberOfGradesInput));
// ---> You should look at using a number formatter so you don't get a million digits
double gradeAverage = getAverage(gradeArray, numberOfGradesInput);
txtMean.setText(Double.toString(gradeAverage));
double standardDeviation = getStdDev(gradeArray, numberOfGradesInput, gradeAverage);
txtStdDeviation.setText(Double.toString(standardDeviation));
} while (numberOfGradesInput < 25);
This code should work a bit more smoothly. Notice how it keeps track of the total number of grades input in numberOfGradesInput and only loops until either a blank entry is encountered or it's reached its maximum. Using enterGrades to track whether you're in the loop works, but the break statement is a much faster, cleaner, and more readable way to do it.
I must warn you to be extremely cautious of your fields! You are declaring a bunch of public fields at the top, then using them as local variables and loop variables. You are even hiding some of these variables with parameter names:
public int numElem;
-vs-
public double getAverage(double[] gradeArray, int numElem) {
This should be avoided to maintain clean code and avoid bugs. The best way to do it is to avoid using public fields whenever possible. By and large, if you only need a value in a certain method once at a time and don't need to remember it in between executions, it should not be a field, let alone a public one. Use instance variables inside your method instead! If possible, create these variables only inside their own loop rather than reusing them. Think of it this way: the farther away a variable can be touched, the more can go wrong. A quick example:
You defined the field public int i;. Let's say you're using that as a loop variable in getAverage(): for (i = 0; i < numElements; i++) {. Now, you also want to use a loop in a method called, say, enterGrades():
for (i = 0; i < 25; i++) {
getAverage(gradeArray, i);
}
Every time you jump over to getAverage(), it's messing with the exact same value you're trying to use to control the other loop you're already in. Problems will occur!
Again, if you don't need variables outside their loop, define them inside it: for (int i = 0; .... If you need to know what number it ended on, just define a local variable right before the loop. And even if you aren't using them, defining fields like public int i when you are accustomed to using those names for loops etc. is just inviting disaster: if you forget to define your local variable i, your IDE probably won't warn you that you're using the public field.
Best of luck.
This line of code:
average = getAverage; // from your if((gradeInput != null) && (gradeInput.length() > 0)) block;
The "getAverage(args)", the average = getAverage() <-- requires parameters to be passed into the method for further operation;
Replace "args" in the brackets with the parameters it requires and it should work;
I'm writing a program to count the number of times the number occurs in a twxt file. The input to the text is given at the run time. The input is stored in the text file, now i have to count the frequency and output the result in another text file.
import java.io.File;
import java.util.Formatter;
import java.util.Scanner;
public class StudentPoll
{
private Scanner x;
int[] frequency = new int[5];
int count =0;
public void openFile(){
try{
x = new Scanner(new File("numbers.txt"));
}
catch(Exception e){
System.out.printf("No File found");
}
}
public void readFile(){
while(x.hasNext()){
int a= x.nextInt();
if(a==1){
frequency[0]=0;
++frequency[0];
break;
}
else if (a== 2){
frequency[1]=0;
++frequency[1];
break;
}
else if( a==3){
frequency[2]=0;
++frequency[2];
break;
}
else if (a==4){
frequency[3]=0;
++frequency[3];
break;
}
else if (a== 5){
frequency[4]=0;
++frequency [4];
break;
}
}
System.out.printf("%s%10s\n","Rating","Frequency");
System.out.printf("%s%10s\n","1",++frequency[0]);
System.out.printf("%s%10s\n","2",++frequency[1]);
System.out.printf("%s%10s\n","3",++frequency[2]);
System.out.printf("%s%10s\n","4",++frequency[3]);
System.out.printf("%s%10s\n","5",++frequency[4]);
}
}
public void closeFile(){
x.close();
}
I should get the output as:
Rating Frequency
1 1
2 2
3 1
4 1
5 1
But the frequency count is incorrect. I don't know what is the error I'm making here.
I also don't know how to write this output to another file. What do I need to change?
You need to take the initialization of your arrays out of the nextInt() part of the loop. Otherwise, every time you find a new number, you reset the count to zero.
Change:
public void readFile(){
while(x.hasNext()){
int a= x.nextInt();
if(a==1){
frequency[0]=0;
++frequency[0];
break;
}
to:
public void readFile(){
while(x.hasNext()){
frequency[0]=0;
frequency[1]=0;
// ... etc etc
int a= x.nextInt();
if(a==1){
++frequency[0];
break;
}
and remove the rest of the frequency[x]=0 from in the loop.
Also, the ++frequency[x] calls in the print statements shouldn't be there. You don't want to increment every time you print the list. It would also make more sense to loop through the arrays, rather than have a printf for each one.
You are resetting the count everytime with frequency[xxx]=0;. Simply remove all those statements as the array elements will automatically be initialised with a default value, which is 0 for int.
frequency[0]=0;
++frequency[0];
you reset frequency every time number matches, and you also increments frequency when printing results.
Replace int[] frequency = new int[5] with
int[] frequency = [0,0,0,0,0] and
System.out.printf("%s%10s\n","1",++frequency[0]); with
System.out.printf("%s%10s\n","1",frequency[0]);