0

I am trying to design a calculator in java. My code isn't finished but I have designed a GUI, which works except for when i try to actually calculate the result. When i press "=" on my calculator i receive the above error. Here is my code:

Problem fixed

I know it is a lot of code so I am sorry for that, and I also realize there may be other errors in there, as I am fairly new to Java, I am just very stuck with the error I'm getting at the moment and have no clue how to fix it, thanks for any help would be greatly appreciated.

1 Answers1

2

You're never initializing calcOperands - so on line 60, when you use:

calcOperands.add(operand);

... calcOperands is still null, causing the exception. It looks like you have the same problem for your other ArrayList variables. You can just create a new list as part of the declaration - and I'd also change the variables themselves to just List<E>, like this:

private final List<Double> calcOperands = new ArrayList<Double>();
private final List<String> calcOperators = new ArrayList<String>();
private final String stringInput;
private final List<Integer> priorityList = new ArrayList<String>();
private String[] splitString;

I've made most of the variables final too, as a matter of course. You might want to consider whether you really want splitString to be mutable, only set if you call checkInput...

(I haven't looked at the rest of your code.)

Besides just fixing these problems, you should take a step back and think about the diagnostics side of things. Which bit were you stuck on when trying to find the problem? Had you looked at the stack trace and pinpointed the problem to StringCalculator.java line 60? Do you understand what NullPointerException means? (And if not, had you tried to find out?) Now that you know the actual answer, it's worth thinking about how you could have reached it yourself - diagnosing issues is an important part of software development.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1 appending this previous [answer](http://stackoverflow.com/a/12688109/2415194) to learn how to read and understand java stacktrace – nachokk Dec 12 '13 at 16:21
  • Thanks a lot sorted it, yeah i could see that it occurred at line 60 but couldn't see why, hence why i found it so frustrating. Thanks for the help. – user3096145 Dec 12 '13 at 19:57