0

I am writing a program that will import values from a txt file in to an array, I then need to count how many of those elements are greater than or equal to 36. The data imports fine, and the total amount of values it displays is correct, but I can not get it display the amount of times the number 36 is found in the file. Thanks for any help!

public static void main(String[] args) throws Exception {
int[] enrollments = new int [100]; 
int count;                        
int  FullClass;                  
double ClassPercentage;          

return count (number of data items)
count = CreateArray(enrollments);
System.out.println (count );


FullClass = AddValues (enrollments);
System.out.println (FullClass)
ClassPercentage= FullClass/count;
System.out.print(ClassPercentage +"% of classes are full");


}//end main 

/**
 *
 * @param classSizes
 */
public static int CreateArray(int[] classSizes) throws Exception{


int count = 0;

File enrollments = new File("enrollments.txt");
Scanner infile = new Scanner (enrollments);

while (infile.hasNextInt()){
      classSizes[count] = infile.nextInt();
      count++}//end while
return count;   //number of items in an array

} // end CreateArray
/**************************************************************************/

/**
 *
 * @throws java.lang.Exception
 */
public static int AddValues (int[] enrollments) throws Exception{
{
int number = 0;
int countOf36s = 0;

while (infile.hasNextInt()) {
      number = infile.next();
      classSizes[count] = number;
      if(number>=36) {
        countOf36s++; 
      }
      count++;
}
return countOf36s;  

}// end AddValues
}//end main
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Andrew1919
  • 17
  • 6
  • Does your file has only numbers in it? And you want the count of all the numbers that are equal to 36? – Prudhvi Feb 25 '15 at 23:07
  • 1
    This `if (count >=36 )` will be true if the read file has at least 36 lines, because `count` is the amount of lines and not a specific number from the file. Change it to `if (enrollments[i] >=36 )` – Tom Feb 25 '15 at 23:18
  • The comment by @Tom will work and be the easiest fix. There are a few stylistic things you might want to address - do you want an answer pointing to some of those? – J Richard Snape Feb 25 '15 at 23:30
  • @Tom Thanks you! I tried to input it in my code and got the same answer. I should place it in my AddValues method, right? – Andrew1919 Feb 26 '15 at 00:43
  • @JRichardSnape That would be great, always looking to learn more, I am painfully new to this. – Andrew1919 Feb 26 '15 at 00:44
  • Your edit has made it so the code won't compile and does change the question quite a lot. I recommend you roll back that edit (or I can do it if you don't know how) and then I'll happily explain stylistic and substantive things you might want to consider (a lot, but not all, of which are already corrected in @prudhvi answer, but you might not have noticed). – J Richard Snape Feb 26 '15 at 15:03

2 Answers2

0

Try this code to count the numbers that are greater than or equal to 36 while you are reading the file only. Change the code in your createArray method or write the below logic where ever you want to.

I tried executing this program. It works as expected. See below code

    import java.util.*;
    import java.io.*;

    public class Test { //Name this to your actual class name
        public static void main(String[] args) throws Exception {
            int[] enrollments = new int [100]; //assuming not more than 100 numbers in the text file
            int count;       //count of all the numbers in text file                 
            int  FullClass;   //count of numbers whose value is >=36               
            double ClassPercentage;
            count = CreateArray(enrollments);
            System.out.println (count);


            FullClass = AddValues (enrollments);
            System.out.println (FullClass);
            ClassPercentage= FullClass/count;
            System.out.print(ClassPercentage +"% of classes are full");
        }

//Method to read all the numbers from the text file and store them in the array
        public static int CreateArray(int[] classSizes) throws Exception {
            int count = 0;
            File enrollments = new File("enrollments.txt"); //path should be correct or else you get an exception.
            Scanner infile = new Scanner (enrollments);
            while (infile.hasNextInt()) {
                classSizes[count] = infile.nextInt();
                count++;
            }
            return count;   //number of items in an array
        } 

//Method to read numbers from the array and store the count of numbers >=36
        public static int AddValues (int[] enrollments) throws Exception{
            int number = 0;
            int countOf36s = 0;
            for(int i=0; i<enrollments.length; i++) {
                number = enrollments[i];
                if(number>=36) {
                    countOf36s++;
                }
            }
            return countOf36s;  
        }
    }
Prudhvi
  • 2,276
  • 7
  • 34
  • 54
  • ok, great, should I replace what I already have in the method with this? Also, yes,the file only contains numbers. – Andrew1919 Feb 26 '15 at 00:47
  • Yes. This logic works fine. Let me know if you have any trouble implementing this. – Prudhvi Feb 26 '15 at 00:59
  • Ok, I replaced my addValues method and still encountered the same issue,is it possible I am calling my methods incorrectly? – Andrew1919 Feb 26 '15 at 01:28
0

Your code indicates that you might have misunderstood a couple of concepts and stylistic things. As you say in your comments you are new at this and would like some guidance as well as the answer to the question - here it is:

Style

  1. Method names and variable names are by convention written starting with a lower case letter and then in camel case. This is in contrast to classes that are named starting with an upper case letter and camel case. Sticking to these conventions make code easier to read and maintain. A full list of conventions is published - this comment particularly refers to naming conventions.

  2. Similarly, by convention, closing braces are put on a separate line when they close loops or if-else blocks.

  3. throws Exception is very general - it's usual to limit as much as possible what Exceptions your code actually throws - in your case throws FileNotFoundException should be sufficient as this is what Scanner or File can throw at runtime. This specificity can be useful to any code that uses any of your code in the future.

Substance

  1. You are creating the array up front with 100 members. You then call CreateArray which reads from a file while that file has more integers in it. Your code does not know how many that is - let's call it N. If N <= 100 (there are 100 integers or less), that's fine and your array will be populated from 0 to N-1. This approach is prone to confusion, though - the length of your array will be 100 no matter how many values it has read from the file - so you have to keep track of the count returned by CreateArray.

    If N > 100 you have trouble - the file reading code will keep going, trying to add numbers to the array beyond its maximum index and you will get a runtime error (index out of bounds)

    A better approach might be to have CreateArray return an ArrayList, which can have dynamic length and you can check how many there are using ArrayList.size()

  2. Your original version of AddValues called CreateArray a second time, even though you pass in the array which already contains the values read from file. This is inefficient as it does all the file I/O again. Not a problem with this small example, but you should avoid duplication in general.

  3. The main problem. As per prudhvi you are checking the number of integers in the file against 36, not each value. You can rectify this as suggested in that answer.

  4. You do ClassPercentage= FullClass/count; Although ClassPercentage is a double, somewhat counter intuitively - because both the variables on the Right Hand Side (RHS) are int, you will have an int returned from the division which will always round down to zero. To make this work properly - you have to change (cast) one of the variables on the RHS to double before division e.g. ClassPercentage= ((double)FullClass)/count;.

  5. If you do keep using arrays rather than ArrayList, be careful what happens when you pass them into methods. You are passing by reference, which means that if you change an element of an array in your method, it remains changed when you return from that method.

  6. In your new version you do

       ...
       classSizes[count] = number;
       if(number>=36) {
       ...
    

    You almost certainly mean

    ...
    number = classSizes[count];
    if(number>=36) {
    ...
    

    which is to say in programing the order of the assignment equals is important, so a = b is not equivalent to b = a

Code

A cleaned up version of your code - observing all the above (I hope):

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

public class ClassCounter
{
    public static void main(String[] args) throws FileNotFoundException
    {
        int count;
        int fullClass;
        double classPercentage;

        ArrayList<Integer> enrollments = createArray();
        count = enrollments.size();
        System.out.println(count);

        fullClass = addValues(enrollments);
        System.out.println(fullClass);
        classPercentage = fullClass / count;
        System.out.print(classPercentage + "% of classes are full");
    }

    /**
     * scans file "enrollments.txt", which must contain a list of integers, and
     * returns an ArrayList populated with those integers.
     *
     * @throws FileNotFoundException
     */
    public static ArrayList<Integer> createArray() throws FileNotFoundException
    {
        ArrayList<Integer> listToReturn = new ArrayList<Integer>();

        File enrollments = new File("enrollments.txt");
        Scanner infile = new Scanner(enrollments);

        while (infile.hasNextInt())
        {
            listToReturn.add(infile.nextInt());
        }

        return listToReturn;   
    } 


     /**
     * returns the number of cases where enrollments >= 36 from the list of 
     * all enrollments
     * 
     * @param enrollments - the list of enrollments in each class
     * @throws FileNotFoundException
     */
    public static int addValues(ArrayList<Integer> enrollments)
    {
        int number = 0;
        int countOf36s = 0;
        int i = 0;

        while (i < enrollments.size())
        {
            number = enrollments.get(i);
            if (number >= 36)
            {
                countOf36s++;
            }
        }

        return countOf36s;
    }
}
Community
  • 1
  • 1
J Richard Snape
  • 20,116
  • 5
  • 51
  • 79