gpt4 book ai didi

java - Try-Catch block 获取字符串长度错误

转载 作者:行者123 更新时间:2023-12-01 11:47:52 25 4
gpt4 key购买 nike

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

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

}
}

}

最佳答案

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

JavaDoc for getText()

关于java - Try-Catch block 获取字符串长度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29013487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com