Try-Catch块获取字符串错误的长度

时间:2015-03-12 15:13:12

标签: java try-catch

我有一切正常但我遇到了JTextField的问题。当用户没有提交任何内容时,它应该返回null而不是0。到目前为止,它返回0,但我需要它返回NULL。即使我把System.out.println("test");放在那里也没有到达Catch区块。

import javax.swing.*;
import javax.*;
import javax.swing.JFrame;

import java.awt.*;
import java.awt.event.*;


public class stringlength implements ActionListener {

  public static JLabel outputLabel;
  public static JTextField inputField = new JTextField(20);

  public static void main(String[] args) {

    stringlength myWindow = new stringlength ();

  }

  public stringlength (){
    JFrame frame = new JFrame("stringlength");
    frame.setVisible(true);
    frame.setSize(500,100);
    //frame.setLayout(new GridLayout(1,3));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    frame.add(panel);

    outputLabel = new JLabel("String length = ");
    JButton stringLengthButton = new JButton("Get String Length");
    stringLengthButton.addActionListener(this);


    panel.add(stringLengthButton);
    panel.add(outputLabel);
    panel.add(inputField);

  }


  public void actionPerformed(ActionEvent e) {

    try{
    String text = inputField.getText();
    System.out.println(text);
    outputLabel.setText("String length = " + text.length());
    }
    catch(NullPointerException e1)
    {
        e1.printStackTrace();

    }
  }

}

3 个答案:

答案 0 :(得分:1)

getText()永远不会返回null。如果您想要null值或异常,则必须检测零长度字符串并返回null或自行抛出异常。

JavaDoc for getText()

答案 1 :(得分:0)

public void actionPerformed(ActionEvent e) {

  try{
    String text = inputField.getText();
    System.out.println(text);
    outputLabel.setText("String length = " + text.length());
    if (text.length()==0)
      throw new NullPointerException();
    }
    catch(NullPointerException e1)
    {
      e1.printStackTrace();
    }
 }

答案 2 :(得分:0)

让我问你......如果你能返回null怎么办?您的代码是否应该让用户第二次尝试输入字符串?如果是,那么试试

    try
        {
        firstTry = inputField.getText();
            if(firstTry.length() == 0)
                {
                    outputLabel.setText("String Length = "+secondTry.length());
                }
            else
                {
                outputLabel.setText("String length = "+firstTry.length());
                }
        }//end try
    catch(NullPointerException e1)
        {
            secondTry=JOptionPane.showInputDialog ( "empty try again" );
            outputLabel.setText("String Length = "+secondTry.length());
        }//end catch