我的编码中的空指针异常概率

时间:2013-04-15 05:51:49

标签: java exception null nullpointerexception

我总是在main方法中的validateCarPlate(nStr)行上获取nullPointerException,并在行上获取(y.matches(rex))。我该如何编辑以删除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);
}

3 个答案:

答案 0 :(得分:2)

改变你那样的方法

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();
}
}

还要输入 computeCheckDigit(y); 方法的代码。

答案 1 :(得分:2)

看起来像

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

返回null

像这样更改代码

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){
     }
   }
  }
}

因为JOptionPane#showInputDialog() {{1}}说 显示请求用户输入的问题消息对话 我认为您忘了提供输入

答案 2 :(得分:1)

如果您点击Cancel按钮,JOptionPane.showInputDialog将返回null。您可以在将nStr传递给validateCarPlate之前检查返回值。如果null返回,只需删除此nStr并继续循环(或根据您的要求将其分解)。