0

Recently got back into using java again. In the below code, if I use getProposal() method inside the try catch block I get no problems however when trying to use the same method outside of the try catch block and in other methods (namely main) I get a null pointer exception (When calling the getProposal() method in the for loop).

public void grabProposals(String fname,Proposal[] proposals) {
                try {
                        props = new File(fname);
                        sc = new Scanner(props).useDelimiter(",");
                } catch (FileNotFoundException f) {
                        System.out.println(f);
                }

                int i = 0;
                while (sc.hasNextLine()) {
                        if (i == proposals.length) break;
                        String prop = sc.nextLine();
                        String delimProp[] = prop.split(",");
                        String sName = null;
                        String pName = null;
                        try {
                                sName = delimProp[0];
                                pName = delimProp[1];
                        } catch (ArrayIndexOutOfBoundsException a) {
                                System.out.println(a);
                        }

                        proposals[i++] = new Proposal(pName,sName);
                }

                for (i = 0;i < proposals.length; i++) {
                        proposals[i].getProposal();
                }

                sc.close();
        }

it2901
  • 69
  • 8
  • where do you get your NPE do you have the stackTrace? what will happen if you cannot create the file and sc is not initialized? why your catch is only to print a line? don't you want to do something when sc cannot be initialized? – vmrvictor Jul 28 '20 at 09:41
  • When you ignore an exception, this happens. You get your FNFEx, which means props is still null, as is sc, thus, `sc.nextLine()` throws. Tip: If you catch an exception, _HANDLE_ it, and 'print something' doesn't count. If you can't (common), then don't catch it. Make this method be declared as 'throws FileNotFoundException', for example. If you can't add that, make your catch block: `throw new RuntimeException("uncaught", e);` instead. – rzwitserloot Jul 28 '20 at 09:42
  • What happens when you have an empty file? Or the file has less lines than `proposals.length`? Then the `proposals` array contains `null` elements, causing the NPE. – f1sh Jul 28 '20 at 09:43

0 Answers0