Jump to content

Help with an assignment using arrays and files

- - - - -

  • Please log in to reply
6 replies to this topic

#1
Hypocrisy

Hypocrisy

    Newbie

  • Members
  • Pip
  • 4 posts
Here's the description of the assignment. I'll post all the code I was able to think of after it.

Assume you work in a tutoring center, which operates Mon-Wed. The center keeps track of how many students come to the center and which tutors they see, similar to the table below:
tutor

Mon

Tue

Wed

Amy

25

3

0

John

14

5

12

Nick

33

22

10

Maria

0

20

5
Write a Java program that does the following:
(1) The program shall read the number of tutors from the command line
c:\> java uin5679hw4 4 into variable numOfTutors. E.g.:
executes the program “uin5679hw4” with “4” as the parameter for the number of tutors.
(2) The program shall read the data as integers from a file named “tutors.txt” into a two-dimensional array
(3) The program shall print the following named tutorData[numOfTutors][3]. (Please note that in the example above, the numbers in bold are in the file and then stored in the array and not the headings of rows/columns). The file has numOfTutors total lines, each line contains 3 integers (number of students per day for a tutor), separated by spaces.
output (underlined
“Total number of students using the center: = values computed from program):
M: value, Tu: value, W: value. Total: value
Tutor1: . (sum of students for each day, sum of all day sums)
value, Tutor2: value, …. Total: value
Max total students per day: . (sum of students for each tutor, sum of all tutor sums)
value
Max students per tutor: . (max of all day sums)
value
Minimum number of students in all slots: . (max of all tutor sums)
value
(4) The program shall use int[] .” (min of all elements of array)
arrays
(5) The program shall use the following to store results for above computations: sumPerDay[3], sumPerTutor[numOfTutors].
methods
• readData() to read the data from the file in (2). The method takes an 2-D int[][] array as parameter (the tutorData) and returns nothing. :
• max1dArray() to calculate the maximum value of a 1-D array, e.g. sumPerDay[]. This method shall take an int[] array as parameter, and return an int as the result.
• min1dArray() to calculate the min value of a 1-D array, e.g. a row of tutorData. This method shall take an int[] array as parameter, and return an int as the result.




Now for my code (note I didn't attempt to put in the output yet as I can't even compile the program.)

import java.io.*;

import java.util.*;

class TutorCenter {

	public static void main(String[] args) throws IOException {  

		int numOfTutors = Integer.parseInt(args[0]);

		Scanner dataFile = new Scanner(new FileReader ("tutors.txt"));

		int[][] tutorData = new int[numOfTutors][3]; 

        for (int i = 0; i < numOfTutors; i++) {

            for(int j = 0; j < 3; j++)

                tutorData[i][j] = dataFile.nextInt();  

		}      

         for (int j = 0; j < tutorData[numOfTutors].length; j++) {

          	int alldaysums = 0;

          	for (int i = 0; i < tutorData[3].length; i++) {

          		alldaysums = alldaysums + tutorData[j][i];

          	}

         }

          	int[] sumPerDay = new int[3];

          	    for (int i = 0; i < tutorData[numOfTutors].length; i++) {

          		sumPerDay[3] = sumPerDay[3] + tutorData[numOfTutors][i];

          	}

          	int[] sumPerTutor = new int[numOfTutors];

          		for (int j = 0; j < tutorData[3].length; j++) {

          		sumPerTutor[numOfTutors] = sumPerTutor[numOfTutors] + tutorData[3][j];	

          	}

          	}

         int max1dArrayDay(int[] sumPerDay) {

         	 int max = sumPerDay[3];

         	 for (int i = 1; i < sumPerDay.length; i++) {

         		 if (sumPerDay[3] > max) {

         			 max = sumPerDay[i];

         			         		 }

         	 }

         	return max;

         	 

         		 }

         int max1dArrayTutor(int[] sumPerTutor) {

        	 int max = sumPerTutor[numOfTutors];

         	 for (int j = 1; j < sumPerTutor.length; j++) {

         		 if (sumPerTutor[numOfTutors] > max) {

         			 max = sumPerTutor[j];

         }

         	 } 

         	 return max;

         		  }

         int min1dArray(int[][] tutorData) {

        	int min = tutorData[numOfTutors][3];  

        	  for(int i = 1; i < tutorData.length; i++){ 

        	    if(tutorData[i][i] < min){  

        	      min = tutorData[i][i];  

        	     }  

        	   }  

        	   return min; 

         }

}


Any form of help will be greatly appreciated, Thanks!

Edited by Roger, 27 November 2010 - 07:11 PM.
added code block


#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
It doesn't compile because max1dArrayTuto and min1dArray don't know the numOfTutors variable. Put it as a class variable instead of only in the main method.

Could you post the content of the txt-file you're trying to read? Cause the first thing you've posted is the output of the program, right?

#3
Hypocrisy

Hypocrisy

    Newbie

  • Members
  • Pip
  • 4 posts
it's a txt file with the following contents:

25 3 0

14 5 12

33 22 10

0 20 5


#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
I've breaked your code up in very small pieces to explain it all, this post is very long.
Every now and then i will say Correct piece the code-block that follows contains a correct chunck of code, containing the corrected code of the previously explained smaller pieces

I also thought there were 3 tutors, so every now and then you'll see me saying there are 3 tutors, but it are 4. The code does not change because of this.
---------------------------------------------------------------------------------------------------------------------

So after doing as my first post says, it compiles (note how the "int" word is gone before numOfTutors in the main method:
Correct piece

class TutorCenter {

    private static int numOfTutors;

    

    public static void main(String[] args) throws IOException {

        numOfTutors = Integer.parseInt(args[0]);

        Scanner dataFile = new Scanner(new FileReader("tutors.txt"));

        int[][] tutorData = new int[numOfTutors][3];

        for (int i = 0; i < numOfTutors; i++) {

            for (int j = 0; j < 3; j++) {

                tutorData[i][j] = dataFile.nextInt();

            }

        }


Then upon running you will get IndexOutOfBoundsException over and over again. This is because you're tyring to access an array or collection with an index that's out of its bounds... (duh :D)
wrong example:

int[] intArray = new int[5];

[COLOR="red"]int[15] = 3;     --> IndexOutOfBoundsException [/COLOR]


What you do is:

int[][] tutorData = new int[numOfTutors][3];

where numOfTutors = 3.
This creates an array tutorData that has 3 rows and columns. But it is zero-based, meaning the first row is number 0 and the last one is number 2,
tutordata[0], tutordata[1], tutordata[2].
What you do is:

tutorData[numOfTutors].length

which is tutorData[3].length, which is not a part of the array. Resulting in IndexOutOfBoundsException

Now, because you create your array as followed (this code is correct):
int[][] tutorData = new int[numOfTutors][3];

tutorData[0].length, tutorData[1].length, tutorData[2].length will always result in 3 because it's coded that way. You can aswell hard code it too, or else change 3 into a variable as the first thing i did with numOfTutors.

Every line that looks like

for (int j = 0; j < [COLOR="red"]tutorData[numOfTutors].length[/COLOR]; j++) {

could be changed into

for (int j = 0; j < 3; j++) {



Which brings me to this piece of code (assume you've corrected it as i did above):

for (int j = 0; j < tutorData[numOfTutors].length; j++) {            //corrected to  j < 3

   int alldaysums = 0;

   for (int i = 0; i < tutorData[3].length; i++) {                          //corrected to  j < 3

     alldaysums = alldaysums + tutorData[j][i];

   }

}

Remember how the array is created this way: int[][] tutorData = new int[numOfTutors][3];
Now you access the array like tutorData[j<3][i<3]; J is not dependant on the numOfTutors. If numOfTutors was 5, J would still count to 3.
so the first for-loop must become:

for (int j = 0; j < numOfTutors; j++) {
And the second loop, as previously mentioned can just be i<3
for (int j = 0; j < 3; j++) {
Just like your first 2 loops, there it was correct.
inside the 2 loops will go his: (i swapped i and j, because i also swapped it in the 2 for loops.:

alldaysums = alldaysums + tutorData[i][j];

You also want to put int alldaysums = 0; outside the 2 for loops, otherwise it will constantly reset to 0 every loop, while you want to keep adding to the total.
Correct piece
int alldaysums = 0;

        for (int j = 0; j < numOfTutors; j++) {            

            for (int i = 0; i < 3; i++) {

                alldaysums = alldaysums + tutorData[j][i];

            }

        }
You may want to remeber these 2 for-loops as these 2 combined, loop trough every element in the array.


Then we have

int[] sumPerDay = new int[3];

for (int i = 0; i < tutorData[numOfTutors].length; i++) {

  sumPerDay[3] = sumPerDay[3] + tutorData[numOfTutors][i];

 }

Again sumPerDay is 3 big, so the max index to use will be 2. Accessing sumPerDay goes like sumPerDay[0], sumPerDay[1] and sumPerDay[2]
sumPerDay[3] will result in anotherIndexOutOfBoundsException
Before continuing we first want to fill up the sumPerDay array with zeros:

for (int i = 0; i < 3; i++) { 

    sumPerDay[i] = 0;              

}


You gonna want to have 2 loops again to have the total sum per day for all 3 tutors.
So let's take our 2 loops again, to loop trough every item in the array.
for (int i = 0; i < numOfTutors; i++) {

  for (int j = 0; j < 3; j++) { 

    tutorData[i][j]               

  }

}
The outer loop with 'i' will loop trough the tutor, and the inner loop with 'j' will loop trough the days. So it goes like: tutor1: day1-day2-day3 | tutor2: day1-day2-day3 | tutor3: day1-day2-day3 .... tutorI: dayJ - dayJ - dayJ
for (int i = 0; i < numOfTutors; i++) {

  for (int j = 0; j < 3; j++) { 

    sumPerDay[j] = sumPerDay[j] + tutorData[i][j];              

  }

}

Correct piece
int[] sumPerDay = new int[3];

        for (int i = 0; i < 3; i++) {

            sumPerDay[i] = 0;               

        }

        for (int i = 0; i < numOfTutors; i++) {

            for (int j = 0; j < 3; j++) {

                sumPerDay[j] += tutorData[i][j];

            }

        }
Note how i did += It's a fancy(shorter) way of doing sumPerDay[j] = sumPerDay[j] + tutorData[i][j];
Simple sample:

int number = 2;

number += 3;   //same like number = number + 3

System.out.println("this should be 5: " + number);

You can do it with any operator you like: +, -, /, *, %



Back to the assignment:
int[] sumPerTutor = new int[numOfTutors];

        for (int j = 0; j < tutorData[3].length; j++) {

            sumPerTutor[numOfTutors] = sumPerTutor[numOfTutors] + tutorData[3][j];

        }
Just like the sumPerDay we want to fill sumPerTutot with zeros first:
int[] sumPerTutor= new int[3];

        for (int i = 0; i < 3; i++) {

            sumPerTutor[i] = 0;               

        }
And also like sumPerDay, we need our 2 loops again to loop trough every element, but instead of sumPerDay[j], it's now sumPerTutor[i]:

for (int i = 0; i < numOfTutors; i++) {

  for (int j = 0; j < 3; j++) {

    sumPerTutor[i] += tutorData[i][j];

  }

}

And then this part is also done


The whole main method is now finished, you can add the following 3 lines to check if everything is correct(assuming there are 3 days, and 4 tutors):
Correct piece

System.out.println("all day sum: "+alldaysums);

System.out.println("sum per day: "+sumPerDay[0] + " | " + sumPerDay[1] + " | " +sumPerDay[2]);

System.out.println("sum per tutor: "+sumPerTutor[0] + " | " +sumPerTutor[1] + " | " +sumPerTutor[2] + " | " +sumPerTutor[3]);



The full class (easier to copy)

import java.io.*;

import java.util.*;


class TutorCenter {


    private static int numOfTutors;


    public static void main(String[] args) throws IOException {

        numOfTutors = Integer.parseInt(args[0]);

        Scanner dataFile = new Scanner(new FileReader("tutors.txt"));

        int[][] tutorData = new int[numOfTutors][3];

        for (int i = 0; i < numOfTutors; i++) {

            for (int j = 0; j < 3; j++) {

                tutorData[i][j] = dataFile.nextInt();

            }

        }


        int alldaysums = 0;

        for (int j = 0; j < numOfTutors; j++) {

            for (int i = 0; i < 3; i++) {

                alldaysums = alldaysums + tutorData[j][i];

            }

        }


        int[] sumPerDay = new int[3];

        for (int i = 0; i < 3; i++) {

            sumPerDay[i] = 0;

        }

        for (int i = 0; i < numOfTutors; i++) {

            for (int j = 0; j < 3; j++) {

                sumPerDay[j] += tutorData[i][j];

            }

        }


        int[] sumPerTutor = new int[numOfTutors];

        for (int i = 0; i < 3; i++) {

            sumPerTutor[i] = 0;

        }

        for (int i = 0; i < numOfTutors; i++) {

            for (int j = 0; j < 3; j++) {

                sumPerTutor[i] += tutorData[i][j];

            }

        }


        System.out.println("all day sum: "+alldaysums);

        System.out.println("sum per day: "+sumPerDay[0] + " | " + sumPerDay[1] + " | " +sumPerDay[2]);

        System.out.println("sum per tutor: "+sumPerTutor[0] + " | " +sumPerTutor[1] + " | " +sumPerTutor[2] + " | " +sumPerTutor[3]);

    }


    int max1dArrayDay(int[] sumPerDay) {

        int max = sumPerDay[3];

        for (int i = 1; i < sumPerDay.length; i++) {

            if (sumPerDay[3] > max) {

                max = sumPerDay[i];

            }

        }

        return max;


    }


    int max1dArrayTutor(int[] sumPerTutor) {

        int max = sumPerTutor[numOfTutors];

        for (int j = 1; j < sumPerTutor.length; j++) {

            if (sumPerTutor[numOfTutors] > max) {

                max = sumPerTutor[j];

            }

        }

        return max;

    }


    int min1dArray(int[][] tutorData) {

        int min = tutorData[numOfTutors][3];

        for (int i = 1; i < tutorData.length; i++) {

            if (tutorData[i][i] < min) {

                min = tutorData[i][i];

            }

        }

        return min;

    }

}



I didn't really look at the 3 other methods.

#5
Hypocrisy

Hypocrisy

    Newbie

  • Members
  • Pip
  • 4 posts
This is amazing thank you so much!!!! I can't wait to analyze your post and learn how to do this properly, thank you :D.

#6
Hypocrisy

Hypocrisy

    Newbie

  • Members
  • Pip
  • 4 posts
After taking all of your advice I came up with this code. I am getting a problem compiling since I tried to call the minimum and maximum methods to add to my output.

import java.io.*;

import java.util.*;


class TutorCenter {


    private static int numOfTutors;


    public static void main(String[] args) throws IOException {

        numOfTutors = Integer.parseInt(args[0]);

        Scanner dataFile = new Scanner(new FileReader("tutors.txt"));

        int[][] tutorData = new int[numOfTutors][3];

        for (int i = 0; i < numOfTutors; i++) {

            for (int j = 0; j < 3; j++) {

                tutorData[i][j] = dataFile.nextInt();

            }

        }


        int alldaysums = 0;

        for (int j = 0; j < numOfTutors; j++) {

            for (int i = 0; i < 3; i++) {

                alldaysums = alldaysums + tutorData[j][i];

            }

        }


        int[] sumPerDay = new int[3];

        for (int i = 0; i < 3; i++) {

            sumPerDay[i] = 0;

        }

        for (int i = 0; i < numOfTutors; i++) {

            for (int j = 0; j < 3; j++) {

                sumPerDay[j] += tutorData[i][j];

            }

        }


        int[] sumPerTutor = new int[numOfTutors];

        for (int i = 0; i < 3; i++) {

            sumPerTutor[i] = 0;

        }

        for (int i = 0; i < numOfTutors; i++) {

            for (int j = 0; j < 3; j++) {

                sumPerTutor[i] += tutorData[i][j];

            }

        }

        int alltutorsums = 0;

        for (int i = 0; i < 3; i++) {

            for (int j = 0; j < numOfTutors; j++) {

                alltutorsums = alltutorsums + tutorData[i][j];

            }

        }

        int maximumDay = max1dArrayDay(sumPerDay);

        int maximumTutor = max1dArrayTutor(sumPerTutor);

        int minimum = min1dArray(tutorData);


        System.out.println("Total number of students using the center:");

        System.out.println("M: "+sumPerDay[0] + " T: " + sumPerDay[1] + " W: " +sumPerDay[2] + " Total: " + alldaysums);

        System.out.println("Tutor1: "+sumPerTutor[0] + " Tutor2: " +sumPerTutor[1] + " Tutor3: " +sumPerTutor[2] + " Tutor4: " +sumPerTutor[3] + " Total: " + alltutorsums);

        System.out.println("Max total students per day: " + maximumDay);

        System.out.println("Mas total students per tutor: " + maximumTutor);

        System.out.println("Minimum number of students in all slots: " + minimum);

    }


    static int max1dArrayDay(int[] sumPerDay) {

        int max = sumPerDay[3];

        for (int i = 1; i < sumPerDay.length; i++) {

            if (sumPerDay[3] > max) {

                max = sumPerDay[i];

            }

        }

        return max;


    }


    static int max1dArrayTutor(int[] sumPerTutor) {

        int max = sumPerTutor[numOfTutors];

        for (int j = 1; j < sumPerTutor.length; j++) {

            if (sumPerTutor[numOfTutors] > max) {

                max = sumPerTutor[j];

            }

        }

        return max;

    }


    static int min1dArray(int[][] tutorData) {

        int min = tutorData[numOfTutors][3];

        for (int i = 1; i < tutorData.length; i++) {

            if (tutorData[i][i] < min) {

                min = tutorData[i][i];

            }

        }

        return min;

    }

}

Its getting "Exception in thread "main" java.lang.ArrayOutOfBoundsException: 3"

#7
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Arrays start counting from 0.

Again, sumPerDay is 3 big, so it's accessed with sumPerDay[0], sumPerDay[1] and sumPerDay[2].
You do sumPerDay[3], which is no part of the array.

Same problem with
int max = sumPerTutor[numOfTutors];
and also
int min = tutorData[numOfTutors][3];

Changing the 3 into 0 solves the first method.
static int max1dArrayDay(int[] sumPerDay) {
        int max = sumPerDay[0];
        for (int i = 1; i < sumPerDay.length; i++) {
            if (sumPerDay[3] > max) {
                max = sumPerDay[i];
            }
        }
        return max;

    }





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users