Results 1 to 7 of 7
Like Tree1Likes
  • 1 Post By Fubarable

Thread: GUI, Arrays, Objects, and Components

  1. #1
    jazob is offline Member
    Join Date
    Dec 2011
    Posts
    10
    Rep Power
    0

    Default GUI, Arrays, Objects, and Components

    I didn't know whether to put this in this forum or the GUI forum so my apologies in advance.
    I am having trouble with Null Pointer exceptions when inputting data from a text file into an array of objects.

    This is the error:
    java.lang.NullPointerException
    at Main.main(Main.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.ru nCommand(JavacCompiler.java:271)

    Here is the code I am working with:
    Java Code:
    import java.awt.* ;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
     
    class Main
    {
      public static void main (String [] args) throws IOException
      {
        //Turn off bold fonts.
        //UIManager.put("swing.boldMetal", Boolean.FALSE);
        int count = 0;
        File fileRead = new File ("keepdata.txt");
        Scanner inFile = new Scanner (fileRead);//All data for each employee is separated by a space.
         
        while (inFile.hasNextLine())
        {
          String line = inFile.nextLine();
          count++;//This will determine how large employee arrays have to be.
        }
         
        Worker [] warehouse = new Worker [count];
         
        while (inFile.hasNextLine())
        {
          for (int i = 0; i < count; i++)
          {
            warehouse[i] = new Worker(i);
            warehouse[i].setName(inFile.next());
            warehouse[i].setMorn(inFile.next());
            warehouse[i].setAft(inFile.next());
            warehouse[i].setNight(inFile.next());
            warehouse[i].setCount(inFile.nextInt());
          }
        }
        //Null Pointer Exception
        System.out.println(warehouse[0].getName());
         
        inFile.close();
         
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
      }
       
      public static void createAndShowGUI()
      {
        MainGUI mGUI = new MainGUI ();
      }
    }// End main class
     
    class MainGUI extends JFrame implements ActionListener
    {
      JFrame frame;
      JPanel buttonPanel; //This panel will contain JButtons that open up the absent employee's schedule.
      JLabel buttonTitle = new JLabel ("Generate schedule for:");
       
      public MainGUI()
      {
        frame = new JFrame("Warehouse Worker Schedules");
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        buttonPanel = new JPanel();
        buttonPanel.setLayout( new BoxLayout( buttonPanel, BoxLayout.Y_AXIS ) );
        buttonPanel.add(buttonTitle);
        add (buttonPanel, BorderLayout.WEST );
      }
       
      public void actionPerformed(ActionEvent event)
      {
        System.exit(0);
      }
    }//End MainGUI class
     
     
    class ScheduleFrame extends JFrame
    {
      //This class will open up the schedule of employees that will cover for a selected absent employee.
      public ScheduleFrame()
      {
      }
    }
     
    class Worker
    {
      //Data of each employee
      private int workerNum;
      private String name;
      private String morn;
      private String aft;
      private String night;
      private int count;
       
      public Worker (int workerNum)
      {
        this.workerNum = workerNum;
      }
      public Worker(String name, String morn, String aft, String night, int count) 
      {
        this.name = name;
        this.morn = morn;
        this.aft = aft;
        this.night = night;
        this.count = count;
      }
       
      public String getName() 
      {
        return name;
      }
      public void setName (String name)
      {
        this.name = name;
      }
       
      public String getMorn() 
      {
        return morn;
      }
      public void setMorn (String morn)
      {
        this.morn = morn;
      }
       
      public String getAft() 
      {
        return aft;
      }
      public void setAft (String aft)
      {
        this.aft = aft;
      }
       
      public String getNight() 
      {
        return night;
      }
       
      public void setNight (String night)
      {
        this.night = night;
      }
       
      public int getCount() 
      {
        return count;
      }
       
      public void setCount(int count) 
      {
        this.count = count;
      }
    }
    The data of employees that work at a warehouse and the shift they work (morning, afternoon, night), as well as a count of how many extra shifts they work (can only be 1 or 0) are from a file.

    The file looks as below, everything on the same line is separated by one space. The first number indicates morning shift, the second afternoon shift, the third night shift, and the fourth is the counter for extra shifts. If the number is a 1, that indicates an employee is already working during that shift. If the number is a 0, that indicates the employee is free during the shift:

    Java Code:
    Jack 1 1 0 0
    Bill 0 1 1 0
    Delilah 0 1 1 0
    Jeff 1 1 0 0
    Jim 1 0 1 0
    Stella 1 0 1 0
    David 1 1 0 0
    Pam 0 1 1 0
    Nicole 1 0 1 0
    Jen 1 1 0 0
    Last edited by jazob; 01-17-2012 at 10:33 PM.

  2. #2
    jazob is offline Member
    Join Date
    Dec 2011
    Posts
    10
    Rep Power
    0

    Default Re: GUI, Arrays, Objects, and Components

    I have edited my first post.
    Last edited by jazob; 01-17-2012 at 10:31 PM.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: GUI, Arrays, Objects, and Components

    You're trying to re-use a Scanner after it has completely read through a file:

    Java Code:
          Scanner inFile = new Scanner(JazobMain.class.getResourceAsStream(RSRC));
    
          while (inFile.hasNextLine()) {
             String line = inFile.nextLine();
             count++;// This will determine how large employee arrays have to be.
          }
    
          Worker[] warehouse = new Worker[count];
    
          while (inFile.hasNextLine()) {
             for (int i = 0; i < count; i++) {
                warehouse[i] = new Worker(i);
                warehouse[i].setName(inFile.next());
                warehouse[i].setMorn(inFile.next());
                warehouse[i].setAft(inFile.next());
                warehouse[i].setNight(inFile.next());
                warehouse[i].setCount(inFile.nextInt());
             }
          }
    This won't work because when you try to read the file's data into your workers, your Scanner's pointer is at the end of the file with no tokens available to be read.

    Why go through the file twice? Why not use one for loop and increment your count and read the line inside this same for loop?
    DarrylBurke likes this.

  4. #4
    jazob is offline Member
    Join Date
    Dec 2011
    Posts
    10
    Rep Power
    0

    Default Re: GUI, Arrays, Objects, and Components

    Quote Originally Posted by Fubarable View Post
    You're trying to re-use a Scanner after it has completely read through a file:

    This won't work because when you try to read the file's data into your workers, your Scanner's pointer is at the end of the file with no tokens available to be read.

    Why go through the file twice? Why not use one for loop and increment your count and read the line inside this same for loop?
    I wanted to go through the file twice so that I would know what dimension to give to my worker array before I populated it with data.
    I'm not sure what you mean about using one for loop. If I merge the two while loops together, how would I initialize my array?
    Did you mean something like this?
    Java Code:
    int i = 0;
    Worker [] warehouse = new Worker [i];
    while (inFile.hasNextLine())
    {
      String line = inFile.nextLine();
      warehouse[i] = new Worker(i);
      warehouse[i].setName(tFile.next());
      warehouse[i].setMorn(tFile.next());
      warehouse[i].setAft(tFile.next());
      warehouse[i].setNight(tFile.next());
      warehouse[i].setCount(tFile.nextInt());
      i++;
    }
    I have fixed the error by using a new Scanner, but I'm still curious to figure out what you mean.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: GUI, Arrays, Objects, and Components

    Either: don't use an array but rather an ArrayList, or use an arbitrarily large array, one likely to be larger than you'll need.

  6. #6
    jazob is offline Member
    Join Date
    Dec 2011
    Posts
    10
    Rep Power
    0

    Default Re: GUI, Arrays, Objects, and Components

    Understood, thank you.
    Last edited by jazob; 01-18-2012 at 09:05 PM.

  7. #7
    jazob is offline Member
    Join Date
    Dec 2011
    Posts
    10
    Rep Power
    0

    Default Re: GUI, Arrays, Objects, and Components

    Is it possible to send variables from two different classes to one class where they can be used together?
    (ie: send a variable X from class A, and another variable Y from class B, where both X and Y are used in a method in class C)
    I am having trouble with instantiating the objects of class C (Schedule in my case) from the other two classes. I am also confused about where I would call my class method if I have two constructors.

    I have commented the method call in both of my Schedule constructors. If I uncomment these lines, I receive a NullPointer Exception:
    java.lang.NullPointerException
    at Schedule.findSub(Main.java:168)
    at Schedule.<init>(Main.java:158)
    at Main.main(Main.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknow n Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Un known Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.ru nCommand(JavacCompiler.java:271)

    I have commented the lines associated with the exception below.
    I am now working on composing my entire application, and I have a section of "commented code" I am trying to incorporate into my program.

    I was looking at this link, which described how to pass an array of objects and use it from various classes: How Do I Pass An Array Of Objects To A Method? - Java | Dream.In.Code

    However, I got confused trying to apply the same logic to my program. The reason why is because the variables I will be using in the commented code, the employee name, is from the MainGUI, and I will also have to use the whole array of Worker objects from the Main class. From the commented code, I will get the employee names to put in the output Schedule frame.

    I need to create a program that will output a schedule of who can cover for an absent employee at the warehouse.
    The name of the absent employee is entered at the main frame in a textbox.
    A new frame pops up that displays two employees who can cover each shift the absent worker works for. (So if the absent worker works the night and morning shifts, the output will display four other employees, 2 for the night shift, 2 for the morning shift)

    Here is the "commented code":
    Java Code:
    /*int x = 0;
     StringBuffer morning = new StringBuffer();
     StringBuffer afternoon = new StringBuffer();
     StringBuffer night = new StringBuffer();
     
     //Look to see which employee's name was entered in the MainGUI 
     for (int d = 0; d < warehouse.length; d++)
     {
     if (warehouse[d].getName().equals(empName))
     {
     x = d;
     }
     }
     
     //If the absent employee works during that shift, find who can cover for them
     if (warehouse[x].getMorn().equals("1"))
     {
     for (int j = 0; j < warehouse.length; j++)
     {
     if ((warehouse[j].getMorn().equals("0")) && (warehouse[j].getCount() == 0))
     {
     morning.append(warehouse[j].getName() + " ");
     warehouse[j].setCount(1);
     }
     }
     }
     
     if (warehouse[x].getAft().equals("1"))
     {
     for (int n = 0; n < warehouse.length; n++)
     {
     if ((warehouse[n].getAft().equals("0")) && (warehouse[n].getCount() == 0))
     {
     afternoon.append(warehouse[n].getName() + " ");
     warehouse[n].setCount(1);
     }
     }
     }
     
     if (warehouse[x].getNight().equals("1"))
     {
     for (int m = 0; m < warehouse.length; m++)
     {
     if ((warehouse[m].getNight().equals("0")) && (warehouse[m].getCount() == 0))
     {
     night.append(warehouse[m].getName() + " ");
     warehouse[m].setCount(1);
     }
     }
     }
     
     //Take only the first two employees that can cover, and set them to the output in the ScheduleFrame.
     String mornCover = morning.toString();
     String aftCover = afternoon.toString();
     String nightCover = night.toString();
     String[] morns = mornCover("\\s+");
     String[] afts = aftCover("\\s+");
     String[] nights = nightCover("\\s+");
     
     String mornSup = morns[0] + ", " + morns[1];
     String aftSup = afts[0] + ", " + afts[1];
     String nightSup = nights[0] + ", " + nights[1];
     */
    I tried to incorporate it into my program by adding in another class, class Schedule, as shown below:

    Java Code:
    import java.awt.* ;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    
    class Main 
    {
      Worker [] warehouse;
      int x = 0;
      public static void main (String [] args) throws IOException
      { 
        File fileRead = new File ("keepdata.txt");
        Scanner inFile = new Scanner (fileRead);
        Scanner tFile = new Scanner (fileRead);
        int aCount = 0;
        while (inFile.hasNextLine())
        {
          String line = inFile.nextLine();
          aCount++;
        }
        Worker [] warehouse = new Worker [aCount];
        int i = 0;
        while (tFile.hasNextLine())
        {
          warehouse[i] = new Worker(i);
          warehouse[i].setName(tFile.next());
          warehouse[i].setMorn(tFile.next());
          warehouse[i].setAft(tFile.next());
          warehouse[i].setNight(tFile.next());
          warehouse[i].setCount(tFile.nextInt());
          i++;
        }
        
        inFile.close();
        int x = 0;
        Schedule app = new Schedule (warehouse, x);//NullPointerException
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
      }
      
      public static void createAndShowGUI()
      {
        MainGUI mGUI = new MainGUI ();
      }
      
    }// End main class
    
    class MainGUI extends JFrame implements ActionListener
    {
      JFrame frame;
      JLabel title = new JLabel ("Input absent employee:");
      JPanel inputPanel = new JPanel ();
      JTextField employee = new JTextField(30);
      JButton run = new JButton("Open Schedule");
      public MainGUI()
      {
        frame= new JFrame("Warehouse Worker Schedules");
        inputPanel.setLayout( new BoxLayout( inputPanel, BoxLayout.Y_AXIS ) );
        run.addActionListener(this);
        run.setActionCommand("run");
        inputPanel.add(title);
        inputPanel.add(employee);
        inputPanel.add(run);
        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.add (inputPanel);
        frame.setSize(400,150);
        frame.setResizable(false);
        frame.setVisible(true);
      }
      
      public void actionPerformed (ActionEvent evt)
      {
        if (evt.getActionCommand().equals("run"))
        {
          String emp = employee.getText();
          Schedule employ = new Schedule (emp);
          String mornSup = employ.getMornSup();
          String aftSup = employ.getAftSup();
          String nightSup = employ.getNightSup();
          ScheduleFrame subframe = new ScheduleFrame (mornSup, aftSup, nightSup);
          
        }
      }
    }
    
    
    class ScheduleFrame extends JFrame 
    {
      //Displays who can cover the worker that's away
      String mornSup;
      String aftSup;
      String nightSup;
      JFrame newframe;
      JLabel firstL = new JLabel ("Morning Shift");
      JTextField firstT = new JTextField (30);
      
      JLabel secondL = new JLabel ("Afternoon Shift");
      JTextField secondT = new JTextField (30);
      
      JLabel thirdL = new JLabel ("Night Shift");
      JTextField thirdT = new JTextField (30);
      
      
      public ScheduleFrame(String first, String second, String third)
      {
        mornSup = first;
        aftSup = second;
        nightSup = third;
        newframe = new JFrame ("Will be covered by:");
        newframe.setLayout(new FlowLayout());
        firstT.setEditable(false);
        firstT.setText(mornSup);
        secondT.setEditable(false);
        secondT.setText(aftSup);
        thirdT.setEditable(false);
        thirdT.setText(nightSup);
        newframe.add(firstL);
        newframe.add(firstT);
        newframe.add(secondL);
        newframe.add(secondT);
        newframe.add(thirdL);
        newframe.add(thirdT);
        newframe.setSize(350,250);
        newframe.setResizable(false);
        newframe.setVisible(true);
      }
    }
    
    class Schedule
    {
      private String mornCover;
      private String aftCover;
      private String nightCover;
      private String mornSup;
      private String aftSup;
      private String nightSup;
      private String emp;
      private int x;
      private Worker [] warehouse;
      
      public Schedule(String e)
      {
        //employee name from MainGUI
        emp = e;
        //findSub();//NullPointerException
      }
      
      public Schedule (Worker [] warework, int y)
      {
        //array of Worker objects and int x
        warework = warehouse;
        x = y;
        //findSub();
      }
      
      public void findSub()
      {
        StringBuffer morning = new StringBuffer();
        StringBuffer afternoon = new StringBuffer();
        StringBuffer night = new StringBuffer();
        
        //Look to see which employee's name was entered in the MainGUI 
         for (int d = 0; d < warehouse.length; d++)//NullPointerException
        {
          if (warehouse[d].getName().equals(emp))
          {
            x = d;
          }
        }
        
        //If the absent employee works during that shift, find who can cover for them
        if (warehouse[x].getMorn().equals("1"))
        {
          for (int j = 0; j < warehouse.length; j++)
          {
            if ((warehouse[j].getMorn().equals("0")) && (warehouse[j].getCount() == 0))
            {
              morning.append(warehouse[j].getName() + " ");
              warehouse[j].setCount(1);
            }
          }
        }
        
        if (warehouse[x].getAft().equals("1"))
        {
          for (int n = 0; n < warehouse.length; n++)
          {
            if ((warehouse[n].getAft().equals("0")) && (warehouse[n].getCount() == 0))
            {
              afternoon.append(warehouse[n].getName() + " ");
              warehouse[n].setCount(1);
            }
          }
        }
        
        if (warehouse[x].getNight().equals("1"))
        {
          for (int m = 0; m < warehouse.length; m++)
          {
            if ((warehouse[m].getNight().equals("0")) && (warehouse[m].getCount() == 0))
            {
              night.append(warehouse[m].getName() + " ");
              warehouse[m].setCount(1);
            }
          }
        }
        
        //Take only the first two employees that can cover, and set them to the output in the ScheduleFrame.
        String mornCover = morning.toString();
        String aftCover = afternoon.toString();
        String nightCover = night.toString();
        //values in the string are separated by spaces
        String[] morns = mornCover.split("\\s+");
        String[] afts = aftCover.split("\\s+");
        String[] nights = nightCover.split("\\s+");
        String mornSup = morns[0] + ", " + morns[1];
        String aftSup = afts[0] + ", " + afts[1];
        String nightSup = nights[0] + ", " + nights[1];
    
      }
          
        public String getMornSup()
        {
          return mornSup;
        }
        
        public String getAftSup()
        {
          return aftSup;
        }
        
        public String getNightSup()
        {
          return nightSup;
        }
      
    }
    
    
    class Worker
    {
      private int workerNum;
      private String name;
      private String morn;
      private String aft;
      private String night;
      private int count;
      
      public Worker (int workerNum)
      {
        this.workerNum = workerNum;
      }
      
      public Worker(String name, String morn, String aft, String night, int count) 
      {
        this.name = name;
        this.morn = morn;
        this.aft = aft;
        this.night = night;
        this.count = count;
      }
      
      public String getName() 
      {
        return name;
      }
      public void setName (String name)
      {
        this.name = name;
      }
      
      public String getMorn() 
      {
        return morn;
      }
      public void setMorn (String morn)
      {
        this.morn = morn;
      }
      
      public String getAft() 
      {
        return aft;
      }
      public void setAft (String aft)
      {
        this.aft = aft;
      }
      
      public String getNight() 
      {
        return night;
      }
      
      public void setNight (String night)
      {
        this.night = night;
      }
      
      public int getCount() 
      {
        return count;
      }
      
      public void setCount(int count) 
      {
        this.count = count;
      }
      
      
    }
    Last edited by jazob; 01-19-2012 at 02:43 AM.

Similar Threads

  1. Arrays of Objects
    By superscout in forum New To Java
    Replies: 2
    Last Post: 01-15-2012, 02:16 PM
  2. How to use class objects in arrays
    By dironic88 in forum Eclipse
    Replies: 6
    Last Post: 04-06-2011, 01:34 PM
  3. scanner objects with arrays again..
    By nevermiind in forum New To Java
    Replies: 18
    Last Post: 05-24-2010, 11:45 AM
  4. Objects and Arrays
    By bannow in forum New To Java
    Replies: 3
    Last Post: 04-19-2010, 07:15 PM
  5. [SOLVED] Arrays of Objects with Subscripts
    By Sidmyre in forum New To Java
    Replies: 5
    Last Post: 12-12-2008, 02:18 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •