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 9 of 9

Thread: Need Help Manipulating 2D Array

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Need Help Manipulating 2D Array

    Hello. I need help with an assignment. The assignment requires me to take user input from a multi dimensional array. That input which is of each employees hours for monday - friday is output in a table.
    It works with an array in which I have hard coded the values. I need to know how to make it so that the values can be from user input.
    Thank you

    import java.util.Scanner;
     
    public class TimeBook  {
     
    private int numberOfEmployees;
    private int[][] hours; //hours[i][j] has the hours for
    //employee j on day i.
    private int[] weekHours; //weekHours[i] has the week's
    //hours worked for employee i + 1.
    private int[] dayHours; //dayHours[i] has the total hours
    //worked by all employees on day i.
    private static final int NUMBER_OF_WORKDAYS = 5;            // rows. 
    private static final int MON = 0;
    private static final int TUE = 1;
    private static final int WED = 2;
    private static final int THU = 3;
    private static final int FRI = 4;
    private static final int NUMBER_OF_EMPLOYEES = 3;           // textbook version has this in main as first line.
     
     
        public static void main(String[] args)
        {
            TimeBook book = new TimeBook(NUMBER_OF_EMPLOYEES);
            book.setHours();
            book.update();   
            book.showTable();
        }
        public TimeBook(int theNumberOfEmployees)
        {
        numberOfEmployees = theNumberOfEmployees;
        hours = new int[NUMBER_OF_WORKDAYS][numberOfEmployees];
        weekHours = new int[numberOfEmployees];
        dayHours = new int[NUMBER_OF_WORKDAYS];    
        }
        public void setHours()
        {
            hours[0][0] = 8; hours[0][1] = 0; hours[0][2] = 9;
            hours[1][0] = 8; hours[1][1] = 0; hours[1][2] = 9;
            hours[2][0] = 8; hours[2][1] = 8; hours[2][2] = 8;
            hours[3][0] = 8; hours[3][1] = 8; hours[3][2] = 4;
            hours[4][0] = 8; hours[4][1] = 8; hours[4][2] = 8;
        }
        public void update()
        {
            computeWeekHours();
            computeDayHours();
        }
        public void computeWeekHours()
        {
            for (int employeeNumber = 1; employeeNumber <=numberOfEmployees; employeeNumber++)
                {//Process one employee:
                int sum = 0;
                for (int day = MON; day <= FRI; day++){
                    sum = sum + hours[day][employeeNumber - 1];
                    //sum contains the sum of all the hours worked in
                    //one
                    //week by the employee with number employeeNumber.
                    weekHours[employeeNumber - 1] = sum;
                }
                }
        }
        private void computeDayHours()
        {
            for (int day = MON; day <= FRI; day++)
            {//Process one day (for all employees):
                int sum = 0;
                for (int employeeNumber = 1;employeeNumber <= numberOfEmployees;
                       employeeNumber++)
                {
                    sum = sum + hours[day][employeeNumber - 1];
                    //sum contains the sum of all hours worked by all
                    //employees on one day.
                    dayHours[day] = sum;
                }
            }
        }
        public void showTable()
        {
            // HEADING BEGIN
            System.out.print("Employee \t");
            for (int employeeNumber = 1;employeeNumber <= numberOfEmployees;            // numberOfEmployees is 3. 
            employeeNumber++)
            {
                System.out.print(employeeNumber + "\t");
            }
            System.out.println("Total");                   //added to display totals after final employee number.
            System.out.println();                           //added to begin next line with day and hours beneath. 
            // HEADING END
     
            // ROWS BEGIN
            for (int day = MON; day <= FRI; day++)
            {
                System.out.print(getDayName(day) + " ");
                for (int column = 0; column < hours[day].length;
                column++)
                {
                    System.out.print(hours[day][column] + "\t");
                    //System.out.println(dayHours[day]);
                }
                System.out.println(dayHours[day]);          //added to display sum of all employee hours for the day under 'Totals' col.
                System.out.println( );
                //System.out.print("Total = ");             // displays total of each employee at bottom line for week. 
     
            }
            System.out.print("Total: \t\t");
            for (int column = 0; column < numberOfEmployees; column++)
            {
                System.out.print(weekHours[column] + "\t");
            }
            //Converts 0 to "Monday", 1 to "Tuesday", etc.
            // ROWS END
     
        }
        private String getDayName(int day)
        {
            String dayName = null;
            switch (day)
            {
            case MON:
            dayName = "Monday  \t";
            break;
            case TUE:
            dayName = "Tuesday \t";
            break;
            case WED:
            dayName = "Wednesday \t";
            break;
            case THU:
            dayName = "Thursday \t";
            break;
            case FRI:
            dayName = "Friday \t\t";
            break;
            default:
            System.out.println("Fatal Error.");
            System.exit(0);


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Need Help Manipulating 2D Array

    I'd recommend a google search of "java scanner" to get started.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need Help Manipulating 2D Array

    How would you fill one variable with a value from the user?

    How would you fill a single dimensional array with the word "FUN" for every element?

    How would you fill a two dimensional array with the word "PARTY" for every element?

    Break your overall problem down into smaller parts. Make a method that will get a valid user input, and assign it to a variable. Then make the code take that value and assign it to an element of an array. Then adapt that to fill the array. From there handle multiple dimensional arrays.

  4. #4
    Junior Member
    Join Date
    Oct 2012
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Need Help Manipulating 2D Array

    In the 'setHours()' method I have created this double for loop. It isn't working though because when I enter something like '8 7 9' for the employee's hours I get an error.
    public void setHours()
        {
            Scanner keyboard = new Scanner(System.in);
            for(int dayhrs=0;dayhrs<=numberOfEmployees;dayhrs++)
            {
                for(int eachday=0;eachday<=NUMBER_OF_WORKDAYS;eachday++)
                {
                    System.out.println("Enter day's hours followed by enter");
                    hours[dayhrs][eachday] = keyboard.nextInt();
                }
            }
        }

  5. #5
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need Help Manipulating 2D Array

    I get an error.


    If we don't know what error you are getting, there is little advice we can offer. Please post your current version of the code and error messages with your question so that everything is available to assist you.

  6. #6
    Junior Member
    Join Date
    Oct 2012
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Need Help Manipulating 2D Array

    Here is the current version of the code
    import java.util.Scanner;
     
    public class TimeBook  {
     
    private int numberOfEmployees;
    private int[][] hours; //hours[i][j] has the hours for
    //employee j on day i.
    private int[] weekHours; //weekHours[i] has the week's
    //hours worked for employee i + 1.
    private int[] dayHours; //dayHours[i] has the total hours
    //worked by all employees on day i.
    private static final int NUMBER_OF_WORKDAYS = 5;            // rows. 
    private static final int MON = 0;
    private static final int TUE = 1;
    private static final int WED = 2;
    private static final int THU = 3;
    private static final int FRI = 4;
    private static final int NUMBER_OF_EMPLOYEES = 3;           // textbook version has this in main as first line.
     
     
        public static void main(String[] args)
        {
            TimeBook book = new TimeBook(NUMBER_OF_EMPLOYEES);
            book.setHours();
            book.update();   
            book.showTable();
        }
        public TimeBook(int theNumberOfEmployees)
        {
        numberOfEmployees = theNumberOfEmployees;
        hours = new int[NUMBER_OF_WORKDAYS][numberOfEmployees];
        weekHours = new int[numberOfEmployees];
        dayHours = new int[NUMBER_OF_WORKDAYS];    
        }
        public void setHours()
        {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Enter work hours. ");
            for(int i=0;i<=NUMBER_OF_WORKDAYS;i++)
            {
                for(int j=0;j<numberOfEmployees;j++)
                {
                    hours[i][j]=keyboard.nextInt();
                }
            }
     
        }
        public void update()
        {
            computeWeekHours();
            computeDayHours();
        }
        public void computeWeekHours()
        {
            for (int employeeNumber = 1; employeeNumber <=numberOfEmployees; employeeNumber++)
                {//Process one employee:
                int sum = 0;
                for (int day = MON; day <= FRI; day++){
                    sum = sum + hours[day][employeeNumber - 1];
                    //sum contains the sum of all the hours worked in
                    //one
                    //week by the employee with number employeeNumber.
                    weekHours[employeeNumber - 1] = sum;
                }
                }
        }
        private void computeDayHours()
        {
            for (int day = MON; day <= FRI; day++)
            {//Process one day (for all employees):
                int sum = 0;
                for (int employeeNumber = 1;employeeNumber <= numberOfEmployees;
                       employeeNumber++)
                {
                    sum = sum + hours[day][employeeNumber - 1];
                    //sum contains the sum of all hours worked by all
                    //employees on one day.
                    dayHours[day] = sum;
                }
            }
        }
        public void showTable()
        {
            // HEADING BEGIN
            System.out.print("Employee \t");
            for (int employeeNumber = 1;employeeNumber <= numberOfEmployees;            // numberOfEmployees is 3. 
            employeeNumber++)
            {
                System.out.print(employeeNumber + "\t");
            }
            System.out.println("Total");                   //added to display totals after final employee number.
            System.out.println();                           //added to begin next line with day and hours beneath. 
            // HEADING END
     
            // ROWS BEGIN
            for (int day = MON; day <= FRI; day++)
            {
                System.out.print(getDayName(day) + " ");
                for (int column = 0; column < hours[day].length;
                column++)
                {
                    System.out.print(hours[day][column] + "\t");
                    //System.out.println(dayHours[day]);
                }
                System.out.println(dayHours[day]);          //added to display sum of all employee hours for the day under 'Totals' col.
                System.out.println( );
                //System.out.print("Total = ");             // displays total of each employee at bottom line for week. 
     
            }
            System.out.print("Total: \t\t");
            for (int column = 0; column < numberOfEmployees; column++)
            {
                System.out.print(weekHours[column] + "\t");
            }
            //Converts 0 to "Monday", 1 to "Tuesday", etc.
            // ROWS END
     
        }
        private String getDayName(int day)
        {
            String dayName = null;
            switch (day)
            {
            case MON:
            dayName = "Monday  \t";
            break;
            case TUE:
            dayName = "Tuesday \t";
            break;
            case WED:
            dayName = "Wednesday \t";
            break;
            case THU:
            dayName = "Thursday \t";
            break;
            case FRI:
            dayName = "Friday \t\t";
            break;
            default:
            System.out.println("Fatal Error.");
            System.exit(0);
            break;
            }
            return dayName;
        }
     
     
     
    }

    and the error I get when running it is this:
    -------------------------------------------------
    run:
    Enter work hours.
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
    at employee.time.records.TimeBook.setHours(TimeBook.j ava:50)
    at employee.time.records.TimeBook.main(TimeBook.java: 31)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 15 seconds)

  7. #7
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need Help Manipulating 2D Array

    You understand an array of 5 elements would be numbered 0 1 2 3 4, right? The error says that you tried to access an element that does not exist. Either an index value of less than zero, or greater than size-1 (hint: the error message has this strange :5 on the end)

    Figure out where the code is trying to access an element of the array that does not exist. If you can not see it in the code, add some printlns to see the values as the code runs. (or a debugger)

  8. The Following User Says Thank You to jps For This Useful Post:

    dansofe0r (October 9th, 2012)

  9. #8
    Junior Member
    Join Date
    Oct 2012
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Need Help Manipulating 2D Array

    And now it works! Thank you very much for your help!
    tumblr_lpqpkj3iAw1qlsz95o1_500.jpg

  10. #9
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need Help Manipulating 2D Array

    I am glad it works.

    If this issue has been solved please mark the thread as solved. Ty

Similar Threads

  1. Array List of Array Lists working for first item but not for second.
    By javapenguin in forum Collections and Generics
    Replies: 6
    Last Post: February 15th, 2012, 05:12 PM
  2. [SOLVED] manipulating collections as/from parameter/arguments
    By chronoz13 in forum Collections and Generics
    Replies: 12
    Last Post: October 1st, 2011, 09:05 PM
  3. Help reading data from file, manipulating then rewriting out.
    By Nismoz3255 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: May 19th, 2011, 09:13 AM
  4. Replies: 2
    Last Post: May 13th, 2011, 03:08 AM
  5. Replies: 2
    Last Post: May 6th, 2011, 05:19 PM