【问题标题】:null pointer exception prob in my coding我的编码中的空指针异常问题
【发布时间】:2013-04-15 05:51:49
【问题描述】:

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

【问题讨论】:

  • computeCheckDigit(y) 在哪里; ?
  • 你检查 y 是否为空?
  • 在哪一行出现错误
  • 请粘贴computeCheckDigit()方法和异常。
  • 对代码块使用一致且符合逻辑的缩进。代码的缩进是为了帮助人们理解程序流程。

标签: java exception null nullpointerexception


【解决方案1】:

看起来像

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

因为,javadocsJOptionPane#showInputDialog()显示一个请求用户输入的问题消息对话框我想你忘了提供输入。

【讨论】:

    【解决方案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);方法的代码。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2012-08-15
        • 1970-01-01
        • 2012-06-13
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-19
        相关资源
        最近更新 更多