0

Null Pointer Error

public int fromRoman(String romanChar)
{   
    int i = 0;
    int total = 0;    
    while (i < romanChar.length()) {                   <----------- THIS LINE

Any idea what this can tell me about how I could go about solving?

I know that fromRoman generally works as when I take out the method in question, it spits out an integer that I can display. But when I add this method

public double getTotal(String whattodo) {

    int number1 = fromRoman(num1);
    int number2 = fromRoman(num2);

    if (whattodo == "*") 
    {
        return (number1 * number2);
    }
    else if (whattodo == "+") 
    {
        return (number1 + number2);
    }

    else if (whattodo == "/") 
    {
        return (number1 / number2);
    }

    else if (whattodo == "-") 
    {            
        return (number1 - number2);
    }

    else 
    {
        throw new NumberFormatException("There is no operation present.");
    }

As well as this in my run method I get a null pointer at the line previously indicated.

double total = getTotal(operator);
Johan Falk
  • 4,341
  • 2
  • 30
  • 42

3 Answers3

1

The parameters num1 and num2 should be not null to parse their, otherwise it throws n NullPointerException.

You should instantiate their before calling of fromRoman function.

  • So now the method works by using the .equals comparison for strings, but I keep getting a 0 for an answer. When you say instantiate you mean something like String num1 = new String(); – user3414479 Mar 13 '14 at 09:47
  • Good Stuff....this helped a lot, and once I changed the string comparison method as PakkuDon mentioned and then I instantiated inside the method before the call as you said....IT WORKED!!!!!!!!!!!!!!!! Thank you very very much for your help. I truly appreciate it. – user3414479 Mar 13 '14 at 09:58
0

Make sure romanChar is not null before starting accessing it in the while-loop. Something like this:

public int fromRoman(String romanChar) {
    if (romanChar == null) {
        return 0;
    }
    int i = 0;
    int total = 0;
    // continue here
Harmlezz
  • 7,972
  • 27
  • 35
  • I don't get the null error until after I add that second method in, So i was assuming it had something to do with that method returning a null somehow?! Not too sure, going to change how I am comparing the strings in the getTotal method to see if that helps. – user3414479 Mar 13 '14 at 09:28
  • Got it squared away. Thanks again for your help. – user3414479 Mar 13 '14 at 10:02
0

if you pass num1 and num2 as null that the only reason its throw nullPointerException so make sure values passed to the fromRoman() method isn't null if it null return back otherwise perform all the operation ..

public int fromRoman(String romanChar)
{ 
if(romanchar==null){
return 0;
 }  
int i = 0;
int total = 0;    
 while (i < romanChar.length()) { 

.

. . .

loknath
  • 1,362
  • 16
  • 25