0

I am always getting nullPointerException on line validateCarPlate(nStr) in the main method and on line if(y.matches(rex)). How should i edit to remove the nullPointerException?

import javax.swing.*;
import java.lang.Exception;

public class Q2{
public static void main(String[]args){
boolean loop = true;
while(loop){
   String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
   try{
       validateCarPlate(nStr);
}
catch(InvalidCarPlateException e){
}
}
}
public static void validateCarPlate(String y)throws InvalidCarPlateException{
String rex = "[a-zA-Z]{3}[0-9]{1,4}";
if(y.matches(rex)){
    computeCheckDigit(y);
}else{
    throw new InvalidCarPlateException();
}
}

public static void computeCheckDigit(String x){
char [] arr = new char[x.length()];
for(int i=0; i<x.length();i++){
    arr[i] = x.charAt(i);
}
6
  • 1
    where is computeCheckDigit(y); ? Commented Apr 15, 2013 at 5:53
  • 3
    Did you check if y is null or not ? Commented Apr 15, 2013 at 5:54
  • At which line it give error Commented Apr 15, 2013 at 5:55
  • Please paste computeCheckDigit() method and exception. Commented Apr 15, 2013 at 5:58
  • Use a consistent and logical indent for code blocks. The indentation of the code is intended to help people understand the program flow. Commented Apr 15, 2013 at 6:07

3 Answers 3

2

Looks like

String nStr = JOptionPane.showInputDialog("Enter car plate number: ");

this returns null

change the code like this

public static void main(String[]args){
  boolean loop = true;
  while(loop){
   String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
   if(nStr != null)
   {
     try{
       validateCarPlate(nStr);
        }
     catch(InvalidCarPlateException e){
     }
   }
  }
}

Since, javadocs for JOptionPane#showInputDialog() says Shows a question-message dialog requesting input from the user I think you forgot to give a input.

Sign up to request clarification or add additional context in comments.

Comments

1

change you method like that

public static void validateCarPlate(String y)throws InvalidCarPlateException{
String rex = "[a-zA-Z]{3}[0-9]{1,4}";
if(y == null){
     // put some message to handle that exception such as
     // JOptionPane.showMessageDialog(null,"Some Message");
}else if(y.matches(rex))
    computeCheckDigit(y);
}else{
    throw new InvalidCarPlateException();
}
}

Also put the code of computeCheckDigit(y); method.

Comments

1

If you click the Cancel button, JOptionPane.showInputDialog will return a null. You can check the return value before passing nStr to validateCarPlate. If a null returned, just drop this nStr and continue the loop (or break it according to your requirement).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.