Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: array problem

  1. #1
    Junior Member darego's Avatar
    Join Date
    Dec 2010
    Location
    Ireland
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default array problem

    hey guys! i'm having trouble adding some stuff from a loop to an array. hopefully someone can help me. i put a comment in my code to show where I'm having trouble

    here's the assignment:
    The Institute of Technology Termonfeckin requires a program to examine students and print out simple reports. Because some of the students in the college are very lazy, the examiners are never sure how many students will turn up at the exam, but there will be at least one. For each student that turns up, the college examines them in 3 subjects. Each subject mark must be entered and a message is printed telling the examiner if the student has gotten honours (75 or over), a pass (50 or over) or failed (under 50). The total marks for each subject is also stored. At the end of the examination when there are no more students, the program prints a short report including the number of students processed, the average mark for each subject and the highest average result from all the subjects.


    1. Create a loop which processes at least one student (but could process any number) and ask the user at the end of it do they want to add another student true/false Done
    2. Create a loop which examines each subject for each student Done
    3. Allow the user to enter grades for students, and print a message about whether they have an honour, pass or fail Done
    4. Create an array to hold the total marks in each subject, add the marks for each student’s grade into this array This is the part I'm having trouble with
    5. When the loop is finished, print out how many students were processed Done
    6. Print out the average mark for each subject (you may use a for loop)
    7. Print out the best average mark of all the subjects


    Below is an example of the output I should have when I'm done:
    Welcome to the Institute of Technology Termonfeckin Exam Processing System
    Please enter marks for subject 1 for student 1
    100
    The student has an honour in this subject
    Please enter marks for subject 2 for student 1
    75
    The student has an honour in this subject
    Please enter marks for subject 3 for student 1
    50
    The student has passed this subject
    Do you want to add another student? true/false
    true
    Please enter marks for subject 1 for student 2
    1
    The student has failed this subject
    Please enter marks for subject 2 for student 2
    2
    The student has failed this subject
    Please enter marks for subject 3 for student 2
    3
    The student has failed this subject
    Do you want to add another student? true/false
    true
    Please enter marks for subject 1 for student 3
    40
    The student has failed this subject
    Please enter marks for subject 2 for student 3
    56
    The student has passed this subject
    Please enter marks for subject 3 for student 3
    78
    The student has an honour in this subject
    Do you want to add another student? true/false
    false
    There were 3 processed today
    The average mark for subject 1 was 47.0
    The average mark for subject 2 was 44.333333333333336
    The average mark for subject 3 was 43.666666666666664
    The best subject average was: 47.0 for subject 1




    my code so far:

    import java.util.Scanner;
    class CA2007
    {
      public static void main(String args[])
      {
        Scanner keyboard = new Scanner(System.in); 
        System.out.println("Welcome to the Institute of Technology Termonfeckin Exam Processing System");
        double[] subject1 = { };
        double[] subject2 = { };
        double[] subject3 = { };
        int processed = 0;
        boolean run = true;
        int student = 0; // needed for student number (student 1, student 2 etc)
        do // loop to process the students Q1
        {
          processed ++; // used to output total students processed Q5
          student ++; // needed for student number (student 1, student 2 etc)
          for(int i = 1; i <= 3; i++) // loop to process each of the 3 subjects Q2
          {
            int mark = 0;
            System.out.println("Please enter marks for subject " + i + " for student " +student);
            mark = keyboard.nextInt();
     
            [COLOR="Red"]// i need to add marks to each subject array here but because it's a loop i'm not sure how.. 
    for example the first time the loop runs i need to add the int mark to to subject1, 
    when the loop runs again i need to add mark to subject2 etc[/COLOR]
     
            if(mark >= 75)
            {
              System.out.println("The student has an honour in this subject");
            }
            else if(mark >= 50)
            {
              System.out.println("The student has passed this subject");
            }
            else if(mark < 50)
            {
              System.out.println("The student has failed this subject");
            }
          }
     
          System.out.println("Do you want to add another student? true/false");
          run = keyboard.nextBoolean();
        }
        while(run == true);
        System.out.println("There were " +processed+ " students processed today"); // outputs total students processed by program Q5
      }
    }

    any help is appreciated!
    Last edited by darego; December 11th, 2010 at 12:53 PM.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: array problem

    There are two ways.

    1) You could create a temporary double[] variable inside the loop. Then you can set that double[] to be equal to one of the subject arrays, based on the value of i. Then when you add to the temporary double[], who is equal to the desired subject array, it will alter the subject array.
    2) Create a 2 dimensional array. This 2 dimensional array will be an array of the double[] for the subjects. You can then reference the corresponding double[] from the 2 dimensional array using the value of i in your loop. This way is much better if you intend on adding more subject arrays later on or if you have an unknown number of subject arrays.

    That is basic information on the two ways. If something is unclear or confusing, ask me which one you would like to know more about and I'll throw together some quick code to explain better.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. The Following User Says Thank You to aussiemcgr For This Useful Post:

    darego (December 11th, 2010)

  4. #3
    Junior Member darego's Avatar
    Join Date
    Dec 2010
    Location
    Ireland
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: array problem

    thanks for the reply!

    i was trying to do something like option 1 but i couldn't manage to make it work, if you had a minute to do an example i'd be grateful! option 2 looks a bit advanced for me but i would love to see how it works.

    thanks again mate.
    Last edited by darego; December 11th, 2010 at 07:01 PM.

  5. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: array problem

    Well I have some questions regarding your project.

    Have you learned about ArrayLists yet (or Vector, or any type of List object)? I ask because of the indication that there could be any number of students. The problem with using an array is its fixed length. List object, however, can increasingly hold objects. The reason this is a problem is because you MUST declare the size of the array before you access it and you cannot add beyond the size of the array. With List objects, you can just keep adding to them and there are no worries. The only way to do that with arrays is to create a new array with a size of 1 larger than the previous, copy over the values, and replace the instance variable each time you add a new student. I really doubt that your professor is wanting you to do that, but who knows.

    Now, I didn't want to edit your code to work with each option (thats the essence of helping without doing) so I took bits of it and tried to demonstrate the theory behind each option. Notice how I declared the size of each array when I created them (for this, I set it to size 1). Also notice how I ignored the user prompting and just did a random number between 0 and 100 for the values (easier for me).

    Option 1:
    class FileOpen
    {
    	public static void main(String args[])
    	{
    		double[] subject1 = new double[1];
    		double[] subject2 = new double[1];
    		double[] subject3 = new double[1];
     
    		for(int i = 1; i <= 3; i++) // loop to process each of the 3 subjects Q2
    		{
    			double[] temp;
    			if(i==1)
    				temp = subject1;
    			else if(i==2)
    				temp = subject2;
    			else
    				temp = subject3;
     
    			double randomNumber = Math.random()*100;
    			temp[0] = randomNumber;
    		}
    	}
    }
    When you use the statement temp = subject3;, it is important to note that you are not creating a duplicate copy of that array. Instead, you are create a reference to that array. So, when we add to our temp array in the loop with the statement: temp[0] = randomNumber;, we are adding the value to the array that is represented by our temp variable name, not just an arbitrary temp array. It is sort of complicated, but once you understand it, it will be one of those eureka moments for you. Basically, when you are assigning one of the arrays to temp, you are giving that array a second (temporary) reference name.

    Option 2:
    class CA2007
    {
    	public static void main(String args[])
    	{
    		/* This create a 2 dimensional array. The values in the bracket are saying
    		 * that the subjects array holds 3 arrays, each of which has a size of 1
    		 */
    		double[][] subjects = new double[3][1];
     
    		for(int i = 1; i <= 3; i++) // loop to process each of the 3 subjects Q2
    		{
    			/* This sets our temp array. Notice 2 significant things with this
    			 * line. 1) our call to the subjects array, where we send it an
    			 * index number. 2) we subtract 1 from the i variable in the index
    			 * index number we send subjects. We do this because the subjects
    			 * array has the indexes of: 0,1,2 instead of 1,2,3
    			 */
    			double[] temp = subjects[i-1];
     
    			double randomNumber = Math.random()*100;
    			temp[0] = randomNumber;
    		}
    	}
    }
    I explained most of what is happening with comments in the code above.

    Alternatively to Option 2, you can actually do that entire loop code in 1 line:
    class CA2007
    {
    	public static void main(String args[])
    	{
    		double[][] subjects = new double[3][1];
     
    		for(int i = 1; i <= 3; i++) // loop to process each of the 3 subjects Q2
    		{
    			subjects[i-1][0] = Math.random()*100;
    		}
    	}
    }


    Do you have any questions? If you have learned any sort of data structures other than array, I will help you use them to make your code more dynamic and applicable for the project.
    Last edited by aussiemcgr; December 11th, 2010 at 08:28 PM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. The Following User Says Thank You to aussiemcgr For This Useful Post:

    darego (December 12th, 2010)

  7. #5
    Junior Member darego's Avatar
    Join Date
    Dec 2010
    Location
    Ireland
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: array problem

    thanks again for the reply. to answer about ArrayLists, no we have not done anymore data structures yet unfortunately (pretty sure we will start in semester 2).

    about option 1, it took me a while but i finally understood it i made a variable that i could use to array position (student number). i will look over option 2 even more when i finish this assignment.

    here's the updated code:

    import java.util.Scanner;
    class CA2007
    {
      public static void main(String args[])
      {
        Scanner keyboard = new Scanner(System.in); 
        System.out.println("Welcome to the Institute of Technology Termonfeckin Exam Processing System");
        double[] subject1 = new double[100];
        double[] subject2 = new double[100];
        double[] subject3 = new double[100];
        int arrayPosition = 0; // needed for student number
        int processed = 0;
        boolean run = true;
        int student = 0; // needed for student number (student 1, student 2 etc)
        do // loop to process the students
        {
          processed ++; // used to output total students processed
          student ++; // needed for student number (student 1, student 2 etc)
          for(int i = 1; i <= 3; i++) // loop to process each of the 3 subjects
          {
            System.out.println("Please enter marks for subject " + i + " for student " +student);
            double mark = keyboard.nextInt();
     
            double[] temp;
            if(i == 1)
            {
              temp = subject1;
            }
            else if(i == 2)
            {
              temp = subject2;
            }
            else
            {
              temp = subject3;
            }
     
            temp[arrayPosition] = mark; // adding student mark to the array
     
            if(mark >= 75)
            {
              System.out.println("The student has an honour in this subject");
            }
            else if(mark >= 50)
            {
              System.out.println("The student has passed this subject");
            }
            else if(mark < 50)
            {
              System.out.println("The student has failed this subject");
            }
          }
          arrayPosition ++; // needed for student number
          System.out.println("Do you want to add another student? true/false");
          run = keyboard.nextBoolean();
        }
        while(run == true);
        System.out.println("There were " +processed+ " students processed today"); // outputs total students processed by program
      }
    }


    now i'm required to do the average mark for each subject using a for loop then print out the best average mark of all the subjects. i was wondering if there is a way to add up all the ints in an int array without doing it like array[0] + array[1] + array[2] etc etc etc because i don't know how many students there will be so it would be a lot of code. thanks again for your time!

  8. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: array problem

    Normally, I would say do the array's length call:
    array.length;
    but, that will just return 100 since that is the size.

    Alternatively, you can go through until you have reached the point where you have added the last one. Now, when you create a double[] of length 100, it creates 100 doubles and sets all of them to 0.0. So, doing it this way will only work if a student cannot score a 0 on in a subject.

    Fortunately, we have an arrayPosition variable that should hold the number of doubles we have added to the array. So, you want to loop through the array:
    //Remember that arrayPosition will contain the length of the array, not the last index we added to.
    for(int i=0;i<arrayPosition-1;i++){...}
    But, there is something very important to remember. If we are going to sum and divide the values, we need to declare a temporary variable outside of the loop:
    double sum=0;
    for(int i=0;i<arrayPosition-1;i++){...}
    Then, we need to go through each spot in the array by using our loop and adding the value at the current index to the sum variable.
    Lastly, after we go through the entire loop and add all of the values, we need to divide sum by arrayPosition to get the average.

    Do that for all 3 of your arrays.
    Last edited by aussiemcgr; December 12th, 2010 at 09:48 AM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. The Following User Says Thank You to aussiemcgr For This Useful Post:

    darego (December 12th, 2010)

  10. #7
    Junior Member darego's Avatar
    Join Date
    Dec 2010
    Location
    Ireland
    Posts
    17
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: array problem

    thanks a lot mate. great help and very nicely explained

Similar Threads

  1. Problem with array
    By mingming8888 in forum What's Wrong With My Code?
    Replies: 9
    Last Post: October 27th, 2010, 12:17 PM
  2. [SOLVED] Array Problem
    By Cammack in forum What's Wrong With My Code?
    Replies: 2
    Last Post: March 5th, 2010, 06:11 PM
  3. [SOLVED] Array Problem
    By KevinGreen in forum Object Oriented Programming
    Replies: 2
    Last Post: January 24th, 2010, 09:07 PM
  4. Problem with 2d array
    By Anyone in forum Collections and Generics
    Replies: 2
    Last Post: November 14th, 2009, 09:32 PM
  5. Java program for 2-D Array Maze
    By Peetah05 in forum Collections and Generics
    Replies: 11
    Last Post: May 8th, 2009, 04:30 AM