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

Thread: Lost in code problem- minor errors causing major problems

  1. #1
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Lost in code problem- minor errors causing major problems

    Java game- has a few errors but i am not sure what to do at this point.

    When the game is run the output box reads-

    Exception in thread "main" java.lang.NullPointerException
    at Creature.<init>(SorcerersCave.java:100)
    at Project3.<init>(Project3.java:64)
    at GUI.<init>(GUI.java:95)
    at GUI.main(GUI.java:597)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 13 seconds)

    file: GUI (set as main file)
     
     
     
     
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.PrintStream;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.text.DefaultCaret;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeSelectionModel;
     
    /**
     * CMSC 335 Project #3
     */
     
    /**
     * @author Roger Joudrey
     */
     
    public final class GUI extends JFrame {
        private static final long serialVersionUID = 1L;
     
     
        public static JPanel getJpJobs() {
            return jpJobs;
        }
     
     
        public static void setJpJobs(JPanel aJpJobs) {
            jpJobs = aJpJobs;
        }
        private JTextField jtfmsg = new JTextField(10);
        private JRadioButton jrbChar, jrbParty, jrbLoot, jrbArt;
        private JButton jbtFile, jbtFear, jbtEmp, jbtCarrCap, jbtTrWeight, jbtTrVal;
        private JTextArea jpTxtArea; 
        private JScrollPane jpScroll;
        private DefaultCaret caret;
        private static JPanel jpJobs = new JPanel();
        private JTree jTree;
     
    public void updateTextArea(final String text) {
      SwingUtilities.invokeLater(new Runnable() {
          @Override
        public void run() {
                    getJpTxtArea().append(text);
                    getJpTxtArea().setTabSize(7);
                    getJpScroll().setPreferredSize(new Dimension(200,600));
        }
      });
    }
     
    public void redir() {
        OutputStream out;
            out = new OutputStream() {
    @Override
    public void write(int b) throws IOException {
       updateTextArea(String.valueOf((char) b));
    }
     
                @Override
                public void write(byte[] b, int off, int len) throws IOException {
       updateTextArea(new String(b, off, len));
    }
     
                @Override
                public void write(byte[] b) throws IOException {
       write(b, 0, b.length);
    }
    };
     
      System.setOut(new PrintStream(out, true));
      System.setErr(new PrintStream(out, true));
     
    } 
     
     
     
    public GUI() throws FileNotFoundException {
            this.jpScroll = new JScrollPane(getJpTxtArea());
     
            this.jpTxtArea = new JTextArea();
     
     
     
        final Project3 cave = new Project3();
     
     
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Sorcerer's Cave");
            jTree = new JTree(top);
            createNodes(top, cave);
            jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            for (int i = 0; i < jTree.getRowCount(); i++) {
            jTree.expandRow(i);
        }
     
            JPanel jpFile = new JPanel();
                jpFile.setLayout(new BorderLayout(5, 0));
                jpFile.add(new JLabel("Choose a source file: "), BorderLayout.WEST);
                jpFile.add(jbtFile = new JButton("Open"), BorderLayout.EAST);
     
            JPanel jpSort1 = new JPanel();
                jpSort1.setLayout(new FlowLayout());
                jpSort1.add(new JLabel("Sort Creatures: "));
                jpSort1.add(jbtFear = new JButton("Fear"));
                jpSort1.add(jbtEmp = new JButton("Empathy"));
                jpSort1.add(jbtCarrCap = new JButton("Carrying Capacity"));
     
            JPanel jpSort2 = new JPanel();
                jpSort2.setLayout(new FlowLayout());
                jpSort2.add(new JLabel("Sort Treasure: "));
                jpSort2.add(jbtTrWeight = new JButton("Weight"));
                jpSort2.add(jbtTrVal = new JButton("Value"));
     
            JPanel jpText = new JPanel();
                jpText.setLayout(new BorderLayout());
                jpText.add(new JLabel("Enter name: "), BorderLayout.WEST);
                jpText.add(jtfmsg, BorderLayout.CENTER);
                jtfmsg.setHorizontalAlignment(JTextField.RIGHT);
     
            JPanel jpRad = new JPanel();
                jpRad.setLayout(new FlowLayout(5));
                jpRad.add(new JLabel("Search by: "));
                jpRad.add(jrbChar = new JRadioButton("Character"));
                jpRad.add(jrbParty = new JRadioButton("Party"));
                jpRad.add(jrbLoot = new JRadioButton("Treasure"));
                jpRad.add(jrbArt = new JRadioButton("Artifact"));
                jrbChar.setSelected(true);
                ButtonGroup group = new ButtonGroup(); 
                    group.add(jrbChar);
                    group.add(jrbParty);
                    group.add(jrbLoot);
                    group.add(jrbArt);
     
            JButton jbtCave;
            JPanel jpBtns = new JPanel();
                jpBtns.setLayout(new GridLayout(1, 50));
                jpBtns.add(new JLabel("Return the elements in the cave:"));
                jpBtns.add(jbtCave = new JButton("Enter... "), BorderLayout.EAST);
     
            JPanel jpSearch = new JPanel();
                jpSearch.setLayout(new GridLayout(1, 2));
                    jpSearch.add(jpRad);
                    jpSearch.add(jpText);
     
            JPanel jpSort = new JPanel();
                jpSort.setLayout(new GridLayout(1, 2));
                jpSort.add(jpSort1);
                jpSort.add(jpSort2);
     
            JPanel jpTop = new JPanel();
            Border searchBorder = BorderFactory.createTitledBorder("Search and Sort");
                jpTop.setLayout(new GridLayout(2, 1));
                    jpTop.setBorder(searchBorder);
                    jpTop.add(jpSearch);
                    jpTop.add(jpSort);
     
            jpJobs.setLayout(new GridLayout(9,1));
     
            JPanel jpMaster = new JPanel();
            Border mainBorder = BorderFactory.createCompoundBorder();
                jpMaster.setBorder(mainBorder);
                jpMaster.setLayout(new BorderLayout(5,25));
                jpMaster.add(jpTop, BorderLayout.NORTH);
                jpMaster.add(jpScroll, BorderLayout.CENTER);
                jpMaster.add(jpBtns, BorderLayout.SOUTH);
                jpMaster.add(jpJobs, BorderLayout.EAST);
                jpMaster.add(new JScrollPane(jTree), BorderLayout.WEST);
     
                caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);//Update scrolling text
            setLayout(new FlowLayout());
                add(jpMaster);
     
            jbtFile.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        Project3.openFile();
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(TextField.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
     
            jrbChar.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                }
            });
     
            jrbParty.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                }
            });
     
            jrbLoot.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                }
            });
     
            jrbArt.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                }
            });
     
            jtfmsg.addActionListener(new ActionListener() {
     
                @Override
                public void actionPerformed(ActionEvent e) {
     
                    if (jrbChar.isSelected() == true){
                        Iterator<Party> partyIterator = cave.getPartyList().iterator();
                        while (partyIterator.hasNext()){
                            Party p = partyIterator.next();
                            Iterator<Creature> creatureIterator = p.getCreatureList().iterator();
                        while (creatureIterator.hasNext()){
                            Creature c = creatureIterator.next();
                        if (c.getName().equals(jtfmsg.getText())){
                            System.out.println("Found: \n" + c.toString() + "\n\t member of " +
                            p.toString() + "\n carrying: \n"  + c.getTreasureList().toString() + c.getArtifactList());
                        break;
                            }
                        }
                        }
                    }                
     
     
                    else if (jrbParty.isSelected() == true){
                    Iterator<Party> partyIterator = cave.getPartyList().iterator();
                        while (partyIterator.hasNext()){
                            Party p = partyIterator.next();
                        if (p.getName().equals(jtfmsg.getText())){
                            System.out.println("Found: \n" + p.toString() + 
                            ", with members: \n" + p.getCreatureList().toString());
                        break;
                            }
                        }
                    }         
     
     
                    else if (jrbLoot.isSelected() == true){
                        Iterator<Party> partyIterator = cave.getPartyList().iterator();
                        while (partyIterator.hasNext()){
                            Party p = partyIterator.next();
                            Iterator<Creature> creatureIterator = p.getCreatureList().iterator();
                        while (creatureIterator.hasNext()){
                            Creature c = creatureIterator.next();
                            Iterator<Treasure> treasureIterator = c.getTreasureList().iterator();
                        while (treasureIterator.hasNext()){
                            Treasure t = treasureIterator.next();
                        if (t.getType().equals(jtfmsg.getText())){
                            System.out.println("Found: \n" + t.toString() + ", carried by " +
                            c.toString() + ", member of \n" + p.toString());
                        break;
                            }
                           }
                          }
                        }
                    }
     
     
                          Iterator<Party> partyIterator = cave.getPartyList().iterator();
                          while (partyIterator.hasNext()){
                              Party p = partyIterator.next();
                              Iterator<Creature> creatureIterator = p.getCreatureList().iterator();
                          while (creatureIterator.hasNext()){
                              Creature c = creatureIterator.next();
                              Iterator<Treasure> treasureIterator = c.getTreasureList().iterator();
                          while (treasureIterator.hasNext()){
                              Treasure t = treasureIterator.next();
                          }
                              Iterator<Artifact> artifactIterator = c.getArtifactList().iterator();
                          while (artifactIterator.hasNext()){
                              Artifact a = artifactIterator.next();
                          if (a.getType().equals(jtfmsg.getText())){
                              System.out.println("Found: \n" + a.toString() + ", carried by " +
                              c.toString() + ", member of " + p.toString());
                          break;
                              }
                             }
                            }
                           }        
                          }
                });
     
            jbtCave.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Iterator<Party> partyIterator = cave.getPartyList().iterator();
                    System.out.println("----------");
                    while (partyIterator.hasNext()){
                        Party p = partyIterator.next();
                        System.out.println("Party " + p.toString() + " has members: ");
                        Iterator<Creature> creatureIterator = p.getCreatureList().iterator();
                    while (creatureIterator.hasNext()){
                        Creature c = creatureIterator.next();
                        System.out.println("     " + c.toString());
                        Iterator<Treasure> treasureIterator = c.getTreasureList().iterator();
                    while (treasureIterator.hasNext()){
                        Treasure t = treasureIterator.next();
                        System.out.println("          " +  
                        "     carrying:     " + t.toString());
                    }
                        Iterator<Artifact> artifactIterator = c.getArtifactList().iterator();
                    while (artifactIterator.hasNext()){
                        Artifact a = artifactIterator.next();
                        System.out.println("          "  
                        + "     carrying:    "  + a.toString());
                    }
                            }
                    System.out.println("----------");
                    }
                    for (Treasure t: cave.getUnfoundTreasure()) {
                        System.out.println(t + " awaits to be found");
                    }
                }
            });
     
            jbtFear.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Collections.sort(cave.getAllCreatures(), new SortFear());
                    System.out.println("----------");
                    System.out.println("Sorted by fear: ");
                    for (Creature c: cave.getAllCreatures()) {
                        System.out.println(c);
                    }
                }
            });
     
            jbtEmp.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Collections.sort(cave.getAllCreatures(), new SortEmpathy());
                    System.out.println("-----------");
                    System.out.println("Sorted by empathy: ");
                    for (Creature c: cave.getAllCreatures()) {
                        System.out.println(c);
                    }
                }
            });
     
            jbtCarrCap.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                Collections.sort(cave.getAllCreatures(), new SortCarrCap());
                    System.out.println("-----------");
                    System.out.println("Sorted by carrying capacity: ");
                    for (Creature c: cave.getAllCreatures()) {
                        System.out.println(c);
                    }
                }
            });    
     
            jbtTrWeight.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                Collections.sort(cave.getAllTreasures(), new SortWeight());
                    System.out.println("----------");
                    System.out.println("Sorted by weight: ");
                    for (Treasure t: cave.getAllTreasures()) {
                        System.out.println(t);
                    }    
                }
            }); 
     
            jbtTrVal.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Collections.sort(cave.getAllTreasures(), new SortValue());
                    System.out.println("----------");
                    System.out.println("Sorted by value: ");
                    for (Treasure t: cave.getAllTreasures()) {
                        System.out.println(t);
                    }    
                }
            });
     
     
            jtfmsg.requestFocusInWindow();
     
        }
     
    public static JPanel getPanel(){
        return getJpJobs();
    }
     
    private void createNodes(DefaultMutableTreeNode top, 
        Project3 cave) {
            DefaultMutableTreeNode party = null;
            DefaultMutableTreeNode creature = null;
            DefaultMutableTreeNode treasure = null;
            DefaultMutableTreeNode artifact = null;
            for (Party p: cave.getPartyList()){
                top.add(party = new DefaultMutableTreeNode("Party -" + p.toString()));
                for (Creature c: p.getCreatureList()){
                    party.add(creature = new DefaultMutableTreeNode(c.getName() + " - " + c.getType()));
                    for (Treasure t: c.getTreasureList()){
                        creature.add(treasure = new DefaultMutableTreeNode(t.getType() + " - " + t.getValue()));
                    }
                    for (Artifact a: c.getArtifactList()){
                        creature.add(artifact= new DefaultMutableTreeNode(a.getName() + " - " + a.getType()));
                    }
                }
            }
            DefaultMutableTreeNode unfound = new DefaultMutableTreeNode("Unfound");
            top.add(unfound);
                for (Treasure t: cave.getUnfoundTreasure()){
                    unfound.add(treasure = new DefaultMutableTreeNode(t.getType() + " - " + t.getValue()));
                }
        }
     
        public JTextArea getJpTxtArea() {
            return jpTxtArea;
        }
     
        public void setJpTxtArea(JTextArea jpTxtArea) {
            this.jpTxtArea = jpTxtArea;
        }
     
        public JScrollPane getJpScroll() {
            return jpScroll;
        }
     
        public void setJpScroll(JScrollPane jpScroll) {
            this.jpScroll = jpScroll;
        }
     
        public DefaultCaret getCaret() {
            return caret;
        }
     
        public void setCaret(DefaultCaret caret) {
            this.caret = caret;
        }
     
    class Jobs extends JPanel implements Runnable, ActionListener{
        private static final long serialVersionUID = 1L;
     
        private boolean goFlag;
     
        private JProgressBar progressBar;
        private String jobName;
        private long jobTime;
        private HashMap <Integer, SorcerersCave> caveMap;
        private long delay;
        private Creature creature;
     
        public Jobs(Creature c){
            this.creature = null;
            this.delay = 200L;
            this.progressBar = new JProgressBar ();
            this.goFlag = false;
            this.creature = c;
            run();
        }
     
     
     
        @Override
         public void actionPerformed (ActionEvent e) {
             if (isGoFlag()) {
                setGoFlag(false);
     
             } 
             else {
                setGoFlag(true);
                synchronized (this) {
                   notify ();}
             }
        }
     
        @Override
        public final void run() {
     
            getProgressBar().setString(getCreature().getJobName());
            getProgressBar().setStringPainted(true); 
     
            JLabel crName = new JLabel(getCreature().getName());
            JButton start = new JButton("Start/Stop");
     
            JPanel crJobs = new JPanel();
                crJobs.setLayout(new FlowLayout());
            crJobs.add(crName);
            crJobs.add(getProgressBar());
            crJobs.add(start);
     
     
            start.addActionListener(this);
     
            JPanel panel = GUI.getPanel();
            panel.add(crJobs);
     
     
            int progress = 0;
            while (progress != 100) {
                try {
                    progress++;
                    getProgressBar().setValue(progress);
                    Thread.sleep(getDelay());
                    synchronized(this){
     
                        while (!isGoFlag()){
                            wait();
                        }
                    }
                } catch (InterruptedException e) {}
            }
     
     
        }
     
     
        public boolean isGoFlag() {
            return goFlag;
        }
     
     
        public void setGoFlag(boolean goFlag) {
            this.goFlag = goFlag;
        }
     
     
        public JProgressBar getProgressBar() {
            return progressBar;
        }
     
     
        public void setProgressBar(JProgressBar progressBar) {
            this.progressBar = progressBar;
        }
     
     
        public String getJobName() {
            return jobName;
        }
     
     
        public void setJobName(String jobName) {
            this.jobName = jobName;
        }
     
     
        public long getJobTime() {
            return jobTime;
        }
     
     
        public void setJobTime(long jobTime) {
            this.jobTime = jobTime;
        }
     
     
        public HashMap <Integer, SorcerersCave> getCaveMap() {
            return caveMap;
        }
     
     
        public void setCaveMap(HashMap <Integer, SorcerersCave> caveMap) {
            this.caveMap = caveMap;
        }
     
     
        public long getDelay() {
            return delay;
        }
     
     
        public void setDelay(long delay) {
            this.delay = delay;
        }
     
     
        public Creature getCreature() {
            return creature;
        }
     
     
        public void setCreature(Creature creature) {
            this.creature = creature;
        }
    }
     
    public static void main(String[] args) throws FileNotFoundException {
            GUI frame = new GUI();
                frame.setTitle("Sorcerer's Cave");
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
     
     
     
        }
    }

    file: Project3
     
     
     
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Scanner;
    import javax.swing.JFileChooser;
     
    /**
     * CMSC 335 Project #3
     */
     
    /**
     * @author Roger Joudrey
     */
     
    public final class Project3 {
     
        private ArrayList<Party> partyList;
        private ArrayList<Treasure> unfoundTreasure;
        private ArrayList<Artifact> unfoundArtifact;
        private ArrayList<Creature> allCreatures;
        private ArrayList<Treasure> allTreasures;
        private ArrayList<Thread> jobList;
        private HashMap <Integer, SorcerersCave> caveMap;
     
        public Project3() throws FileNotFoundException {
            this.caveMap = new HashMap<>();
            this.jobList = new ArrayList<>();
            this.allTreasures = new ArrayList<>();
            this.allCreatures = new ArrayList<>();
            this.unfoundArtifact = new ArrayList<>();
            this.unfoundTreasure = new ArrayList<>();
            this.partyList = new ArrayList<>();
     
     
            Scanner input = new Scanner(openFile());
     
     
            while (input.hasNextLine()) {
                String line = input.nextLine().replaceAll(" ", "");
     
                if (!line.isEmpty()) {
     
                    Scanner output = new Scanner(line).useDelimiter(":");
     
                    String check = output.next();
                    switch (check) {
                        case "p":
     
                            Party p = new Party(output.nextInt(), output.next(), getCaveMap(), getAllCreatures());
                            partyList.add(p);
                            break;
                        case "c":
                            {
                                int index = output.nextInt();
                                String type = output.next();
                                String name = output.next();
                                int partyIndex = output.nextInt();
                                int empathy = output.nextInt();
                                int fear = output.nextInt();
                                double carryingCap = output.nextDouble();
                                Creature c = new Creature(index, type, name, partyIndex,
                                         empathy, fear, carryingCap, getPartyList(), getCaveMap(), getAllCreatures());
                                allCreatures.add(c);
                                break;
                            }
                        case "t":
                            {
                                int index = output.nextInt();
                                String type = output.next();
                                int creatureIndex = output.nextInt();
                                double weight = output.nextDouble();
                                int value = output.nextInt();
                                Treasure t = new Treasure(index, type, creatureIndex, weight, 
                                        value, getPartyList(), getUnfoundTreasure(), getCaveMap(), getAllTreasures());
                                allTreasures.add(t);
                                break;
                            }
                        case "a":
                            {
                                int index = output.nextInt();
                                String type = output.next();
                                int creatureIndex = output.nextInt();
                                String name = output.next();
                                Artifact a = new Artifact(index, type, creatureIndex, name, getPartyList(), getUnfoundArtifact(), getCaveMap());
                                unfoundArtifact.add(a);
                                break;
                            }
                        case "j":
                            {
                                int index = output.nextInt();
                                String jobName = output.next();
                                int target = output.nextInt();
                                long time = output.nextLong();
                                Creature c = (Creature)(caveMap.get(target));
                                Thread j = new Thread(c);
                                jobList.add(j);
                                c.setJobName(jobName);
                                j.start();
                                break;
                            }
                    }
     
                }
     
            }
     
        }
     
     
     
     
        public static File openFile() throws FileNotFoundException {
            JFileChooser fileChooser = new JFileChooser(".");
            File fileChoice = null;
            if (fileChooser.showOpenDialog(null)
                    == JFileChooser.APPROVE_OPTION) {
                fileChoice = fileChooser.getSelectedFile();
                try (Scanner input = new Scanner(fileChoice)) {
                    while (input.hasNext()) {
                        System.out.println();
                        input.nextLine();
                    }
                }
            } else {
                System.out.println("No file Selected");
            }
            return fileChoice;
        }
     
        public void addTreasure(Treasure t){
            getUnfoundTreasure().add(t);
        }
     
        public void addArtifact(Artifact a){
            getUnfoundArtifact().add(a);
        }
     
        public ArrayList<Party> getPartyList() {
            return partyList;
        }
     
     
        public void setPartyList(ArrayList<Party> partyList) {
            this.partyList = partyList;
        }
     
     
        public ArrayList<Treasure> getUnfoundTreasure() {
            return unfoundTreasure;
        }
     
     
        public void setUnfoundTreasure(ArrayList<Treasure> unfoundTreasure) {
            this.unfoundTreasure = unfoundTreasure;
        }
     
     
        public ArrayList<Artifact> getUnfoundArtifact() {
            return unfoundArtifact;
        }
     
     
        public void setUnfoundArtifact(ArrayList<Artifact> unfoundArtifact) {
            this.unfoundArtifact = unfoundArtifact;
        }
     
     
        public ArrayList<Creature> getAllCreatures() {
            return allCreatures;
        }
     
     
        public void setAllCreatures(ArrayList<Creature> allCreatures) {
            this.allCreatures = allCreatures;
        }
     
     
        public ArrayList<Treasure> getAllTreasures() {
            return allTreasures;
        }
     
     
        public void setAllTreasures(ArrayList<Treasure> allTreasures) {
            this.allTreasures = allTreasures;
        }
     
     
        public ArrayList<Thread> getJobList() {
            return jobList;
        }
     
     
        public void setJobList(ArrayList<Thread> jobList) {
            this.jobList = jobList;
        }
     
     
        public HashMap <Integer, SorcerersCave> getCaveMap() {
            return caveMap;
        }
     
     
        public void setCaveMap(HashMap <Integer, SorcerersCave> caveMap) {
            this.caveMap = caveMap;
        }
     
    }

    file: SorcerersCave
     
     
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.HashMap;
    import javax.swing.JProgressBar;
     
    /**
     * CMSC 335 Project #3
     */
     
    /**
     * @author Roger Joudrey
     */
     
    public class SorcerersCave {
     
    }
    class Party extends SorcerersCave{
        private int index;
        private String name;
        private ArrayList<Creature> creatureList;
     
     
        public Party(){
            this.creatureList = new ArrayList<>();
        }
     
        public Party(int index, String name, HashMap<Integer, SorcerersCave> caveMap, 
                ArrayList<Creature> allCreatures){
            this.creatureList = new ArrayList<>();
            this.index = index;
            this.name = name;
            caveMap.put(index, this);
        }
     
     
        @Override
        public String toString(){
            return name;
        }
     
        public int getIndex(){
            return this.index;
        }
     
        public String getName(){
            return this.name;
        }
     
        public void addCreature(Creature c){
            getCreatureList().add(c);
        }
     
     
        public ArrayList<Creature> getCreatureList() {
            return creatureList;
        }
     
     
        public void setCreatureList(ArrayList<Creature> creatureList) {
            this.creatureList = creatureList;
        }
     
    }
     
    class Creature extends SorcerersCave implements Runnable, ActionListener{
        private int index;
        private String type;
        private String name;
        private int partyByIndex;
        private int empathy;
        private int fear;
        private double carryingCapacity;
        private ArrayList<Treasure> treasureList;
        private ArrayList<Artifact> artifactList;
        private boolean goFlag = false;
     
        private JProgressBar progressBar;
        private String jobName;
        private long jobTime;
     
     
     
        public Creature(int index, String type, String name, int partyByIndex, int empathy,
                int fear, double carryingCapacity, ArrayList<Party> partyList, 
                HashMap<Integer, SorcerersCave> caveMap, ArrayList<Creature> allCreatures){
            this.progressBar = new JProgressBar ();
            this.artifactList = new ArrayList<>();
            this.treasureList = new ArrayList<>();
            this.index = index;
            this.type = type;
            this.name = name;
            this.partyByIndex = partyByIndex;
            this.empathy = empathy;
            this.fear = fear;
            this.carryingCapacity = carryingCapacity;
            caveMap.put(index, this);
            ((Party)caveMap.get(this.partyByIndex)).addCreature(this);
            allCreatures.add(this);
        }
     
     
        @Override
        public String toString(){
            return index + "\t" + name + "\t" + type + "\t" + empathy + "\t" + fear + "\t"  
                    + carryingCapacity;
        }
     
     
        public int getIndex(){
            return this.index;
        }
     
     
        public String getType(){
            return this.type;
        }
     
     
        public String getName(){
            return this.name;
        }
     
     
        public int getPartyByIndex(){
            return this.partyByIndex;
        }
     
     
        public int getEmpathy(){
            return this.empathy;
        }
     
     
        public int getFear(){
            return this.fear;
        }
     
     
        public double getCarryingCap(){
            return this.carryingCapacity;
        }
     
        public void addTreasure(Treasure t){
            getTreasureList().add(t);
        }
     
        public void addArtifact(Artifact a){
            getArtifactList().add(a);
        }
     
        public void addJob(long time){
            setJobTime(time);
        }
     
        public void setJobName(String jobName){ 
            this.jobName = jobName; }
     
        @Override
        public void run() {
            Jobs jobs = new Jobs(this);
        }
     
        @Override
        public void actionPerformed(ActionEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
     
     
        public boolean isGoFlag() {
            return goFlag;
        }
     
     
        public void setGoFlag(boolean goFlag) {
            this.goFlag = goFlag;
        }
     
     
        public ArrayList<Treasure> getTreasureList() {
            return treasureList;
        }
     
     
        public void setTreasureList(ArrayList<Treasure> treasureList) {
            this.treasureList = treasureList;
        }
     
     
        public ArrayList<Artifact> getArtifactList() {
            return artifactList;
        }
     
     
        public void setArtifactList(ArrayList<Artifact> artifactList) {
            this.artifactList = artifactList;
        }
     
     
        public JProgressBar getProgressBar() {
            return progressBar;
        }
     
     
        public void setProgressBar(JProgressBar progressBar) {
            this.progressBar = progressBar;
        }
     
     
        public String getJobName() {
            return jobName;
        }
     
     
        public long getJobTime() {
            return jobTime;
        }
     
     
        public void setJobTime(long jobTime) {
            this.jobTime = jobTime;
        }
     
        private static class Jobs {
     
            public Jobs() {
            }
     
            private Jobs(Creature aThis) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        }
     
    }
     
    class Treasure extends SorcerersCave{
        private int index;
        private String type;
        private int creature;
        private double weight;
        private int value;
     
     
        public Treasure(int index, String type, int creature, double weight, int value,
                ArrayList<Party> partyList, ArrayList<Treasure> unfoundTreasure, 
                HashMap<Integer, SorcerersCave> caveMap, ArrayList<Treasure> allTreasures){
            this.index = index;
            this.type = type;
            this.creature = creature;
            this.weight = weight;
            this.value = value;
            allTreasures.add(this);
            caveMap.put(index, this);
            if (this.creature == 0){
                unfoundTreasure.add(this);
            }
            else{
     
                ((Creature)caveMap.get(this.creature)).addTreasure(this);
     
            }
     
        }
     
     
        @Override
        public String toString(){
            return index + "\t" + type + "\t" + weight + "\t" + value;
        }
     
        public int getIndex(){
            return this.index;
        }
     
     
        public String getType(){
            return this.type;
        }
     
     
        public int getCarryingCreature(){
            return this.creature;
        }
     
     
        public double getWeight(){
            return this.weight;
        }
     
     
        public int getValue(){
            return this.value;
        }
     
    }
     
    class Artifact extends SorcerersCave{
        private int index;
        private String type;
        private int creature;
        private String name;
     
     
        public Artifact(int index, String type, int creature, String name,
                ArrayList<Party> partyList, ArrayList<Artifact> unfoundArtifact, 
                HashMap<Integer, SorcerersCave> caveMap){
            this.index = index;
            this.type = type;
            this.creature = creature;
            this.name = name;
            caveMap.put(index, this);
            if (this.creature == 0){
                unfoundArtifact.add(this);
            }
            else {
                ((Creature)caveMap.get(this.creature)).addArtifact(this);        }
            }
     
     
        @Override
        public String toString(){
            return index + "\t" + type;
        }
     
     
        public int getIndex(){
            return this.index;
        }
     
     
        public String getType(){
            return this.type;
        }
     
     
        public String getName(){
            return this.name;
        }
     
     
        public int getCreatureIndex(){
            return this.creature;
        }
     
    }
     
    class SortValue implements Comparator<Treasure> {
     
        @Override
        public int compare(Treasure o1, Treasure o2) {
            int value1 = o1.getValue();
            int value2 = o2.getValue();
            if (value1 < value2) {
                return -1;
            } else if (value1 == value2) {
                return 0;
            } else {
                return 1;
            }
        }
     
    }
     
    class SortWeight implements Comparator<Treasure> {
     
        @Override
        public int compare(Treasure o1, Treasure o2) {
            double weight1 = o1.getWeight();
            double weight2 = o2.getWeight();
            if (weight1 < weight2) {
                return -1;
            } else if (weight1 == weight2) {
                return 0;
            } else {
                return 1;
            }
        }
     
    }
     
    class SortCarrCap implements Comparator<Creature> {
     
        @Override
        public int compare(Creature o1, Creature o2) {
            double carrCap1 = o1.getCarryingCap();
            double carrCap2 = o2.getCarryingCap();
            if (carrCap1 < carrCap2) {
                return -1;
            } else if (carrCap1 == carrCap2) {
                return 0;
            } else {
                return 1;
            }
        }
     
    }
     
    class SortEmpathy implements Comparator<Creature> {
     
        @Override
        public int compare(Creature o1, Creature o2) {
            int emp1 = o1.getEmpathy();
            int emp2 = o2.getEmpathy();
            if (emp1 < emp2) {
                return -1;
            } else if (emp1 == emp2) {
                return 0;
            } else {
                return 1;
            }
        }
     
    }
     
    class SortFear implements Comparator<Creature> {
     
        @Override
        public int compare(Creature o1, Creature o2) {
            int fear1 = o1.getFear();
            int fear2 = o2.getFear();
            if (fear1 < fear2) {
                return -1;
            } else if (fear1 == fear2) {
                return 0;
            } else {
                return 1;
            }
        }
     
    }


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Lost in code problem- minor errors causing major problems

    You're trying to use a variable that holds a null reference on line 100 of SorcerersCave.java. You will want to check the variables on that line, find out which one is null, and look back into your code to find a place to initialize it before you use it.

    Note that I see that your code is mis-using inheritance. There is no way that Creature or Artifact should extend SourcerersCave since they both fail the "is-a" rule: neither sub class is a more specialized version of the parent class.

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

    roj3og (March 9th, 2013)

  4. #3
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Lost in code problem- minor errors causing major problems

    i set them to extend the SorceresCave because they are elements in the game, is this not right?

  5. #4
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Lost in code problem- minor errors causing major problems

    Quote Originally Posted by roj3og View Post
    i set them to extend the SorceresCave because they are elements in the game, is this not right?
    Being elements in the game is not a reason for them to inherit the class. For inheritance to work, again the child classes need to be more specialized versions of the parent class. There's no way that I can conceive of a Creature or an Artifact to be more specialized versions of the game class, no way. I fear that this may be the source of your problem, but I can't tell since I do not know which line of your code is the one that threw the exception.

  6. #5
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Lost in code problem- minor errors causing major problems

    Exception in thread "main" java.lang.NullPointerException
    at Creature.<init>(SorcerersCave.java:100)
    at Project3.<init>(Project3.java:64)
    at GUI.<init>(GUI.java:95)
    at GUI.main(GUI.java:597)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 11 seconds)
    sorcerescave100
     ((Party)caveMap.get(this.partyByIndex)).addCreature(this);
    project3 64
    Creature c = new Creature(index, type, name, partyIndex,
                                         empathy, fear, carryingCap, getPartyList(), getCaveMap(), getAllCreatures());
    gui 95
    final Project3 cave = new Project3();
    gui 597
    GUI frame = new GUI();

  7. #6
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Lost in code problem- minor errors causing major problems

    Consider adding some debug lines in your code such as:

          System.out.println("partyByIndex: " + partyByIndex);
          SorcerersCave foo = caveMap.get(partyByIndex);
          System.out.println("foo: " + foo); // I'm betting this will return -- foo: null
     
          ((Party) caveMap.get(this.partyByIndex)).addCreature(this);

    Then figure out why the Map doesn't hold what you think it holds.

    Update on answer: I think that your SourcerersCave class should perhaps be an interface not a class, a "marker" interface much like Serializable is a marker interface.

  8. #7
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Lost in code problem- minor errors causing major problems

    this is what it output:

    partyByIndex: 10001
    foo: Unity
    partyByIndex: 10001
    foo: Unity
    partyByIndex: 10003
    foo: Conglomeration
    partyByIndex: 10002
    foo: Assemblage
    partyByIndex: 10002
    foo: Assemblage
    partyByIndex: 10003
    foo: Conglomeration
    partyByIndex: 10001
    foo: Unity
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at Project3.<init>(Project3.java:86)
    at GUI.<init>(GUI.java:95)
    at GUI.main(GUI.java:597)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 13 seconds)

    I forgot to include the file that this is supposed to run in initial post: The Sample Data-

    // sample data file
    // Parties format:
    // p:<index>:<name>
    p : 10001 : Unity
    p : 10002 : Assemblage
    p : 10003 : Conglomeration
    // Creatures format:
    // c:<index>:<type>:<name>:<party>:<empathy>:<fear>:< carrying capacity>
    c : 20001 : Woman : Lucy :10001 : 17 : 22 : 20
    c : 20002 : Woman : Jane :10001 : 22 : 15 : 25
    c : 20003 : Woman : Nancy :10003 : 80 : 44 : 20
    c : 20004 : Man : James :10002 : 35 : 13 : 50
    c : 20005 : Troll : Fred :10002 : 03 : 05 : 150
    c : 20006 : Warlock : Harry :10003 : 05 : 06 : 0
    c : 20007 : Witch : Morgana:10001 : 10 : 15 : 0
    // Treasures format:
    // t:<index>:<type>:<creature>:<weight>:<value>
    // creature = 0 means noone is carrying that treasure at the moment
    t : 30001 : Gold : 20004 : 50 : 2000
    t : 30002 : Gold : 0 : 75 : 5000
    t : 30003 : Gems : 20002 : 10 : 10000
    t : 30004 : Silver : 20005 : 120 : 1000
    // Artifacts format:
    // a:<index>:<type>:<creature>[:<name>]
    a : 40001 : Wand : 20007 : ElderWand
    a : 40002 : Wand : 20006
    a : 40003 : Potion : 20007

  9. #8
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Lost in code problem- minor errors causing major problems

    That's not a NullPointerException but rather a NoSuchElementException usually thrown by a Scanner object, and that's a whole different issue!

    --- Update ---

    Use more debugging statements to see which line is causing the problem. I would print each line once obtained before trying to scan the individual line, and then see which line causes the error. Once you see which line of text is causing the error and which line of code is causing it, the cause will be obvious to you, and so will the solution. Note that that particular type of line of text is different in what it allows than all of the types of line. (hint)

  10. The Following User Says Thank You to curmudgeon For This Useful Post:

    roj3og (March 9th, 2013)

  11. #9
    Junior Member
    Join Date
    Mar 2013
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Lost in code problem- minor errors causing major problems

    What do you think I should do then?

    --- Update ---

    I'm not quite sure I understand.

  12. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Lost in code problem- minor errors causing major problems

    You need to print out the full text of the String that is read BEFORE breaking it into tokens with the Scanner class methods so you can see what line is causing the problem.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Replies: 1
    Last Post: June 9th, 2012, 11:29 AM
  2. my code displaying some minor wrong o/p ....plz suggest me an answer !
    By naved in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 28th, 2011, 11:59 AM
  3. Cannot find where extra brace is at causing my errors
    By eagle09 in forum What's Wrong With My Code?
    Replies: 15
    Last Post: June 27th, 2011, 07:30 PM
  4. Persistence causing problems with JButton 2D Array
    By easyp in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 21st, 2010, 12:21 PM
  5. Having problems with String out of bounds errors
    By Bill_H in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 27th, 2009, 02:47 PM