java - 检查字符串长度返回 NullPointerException?

标签 java string

出于某种原因,我在检查“if”语句中的字符串长度时收到 NullPointerException。我可能做错了,但我真的不知道。我尝试编写的代码基本上只是更改按钮的标签,但前提是字符串“label1”的长度为 0 个字符(或未设置),因此它只能更改一次。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

         public class Class1 {

public static String label1;


public static String one = ("Hello");
public static String two = ("Goodbye");

public static void main(String args[]) {

    JFrame frame = new JFrame();
    JPanel pane = new JPanel();
    JButton button = new JButton();


    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
            if(label1.length() == 0) {

                label1 = one;
                JButton button = (JButton) e.getSource();
                button.setText(label1);
            }
            if(label1.length() < 0) {

                label1 = two;
                JButton button = (JButton) e.getSource();
                button.setText(label1);
            }
        } catch(Exception ex) {
                System.out.println("ERROR");
                ex.printStackTrace();
            }

        }       
    });

    frame.setSize(350, 350);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(pane);
    pane.add(button);


     }

 }

最佳答案

public static String label1;

要使用 if(label1.length() == 0) { 行,您必须在 lable1 之前初始化

你没有初始化标签!任何地方任何人都可以使用它

尝试改变那条线

public static String label="";

或添加额外的空条件

if(label1 != null && label1.length() == 0) {

关于java - 检查字符串长度返回 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17183322/

相关文章:

java - 在存储过程执行期间设置参数

java - 错误 :Execution failed for task ':app:dexDebug' at runtime

java - 如何在导入的非 Maven 项目上使用 Maven (Eclipse Keppler)

c - scanf 拾取空格后的字符 C

c - 输入长度未知

c# - 如何从 C# 中的字符串中获取最后四个字符?

java - float .NaN == float .NaN

java - 我运行 tomcat 的 redhat 机器上的有效 Xmx 值是多少

c# - 检测*所有*表情符号

c - 使用函数反转 C 中的字符串