문제

Here is my code :

if (ChoixPortCom.equals(null) == true ) JOptionPane.showMessageDialog(null, "Choose Port COM");

and I get the famous java.lang.NullPointerException

My JCombobox is filled like : 1st -> nothin/empty null no String nothing 2nd -> COM1 3nd -> COM2 ....

Why is "if" condition not right ?

도움이 되었습니까?

해결책

choixPortCom.equals(null) will never be true. If choixPortCom is not null, then the expression will return false as expected. If choixPortCom is null, then the expression will throw a NullPointerException, since you are attempting to call a method on null; this is what's happening in your case. The appropriate way to check for null is:

if (choixPortCom == null)  // I've assumed a more common naming convention

There is also an Objects class in Java 7 that has some useful methods for null-checking. For example, Objects.requireNonNull():

Objects.requireNonNull(choixPortCom, "input can't be null!")

다른 팁

It should be

if (ChoixPortCom == null)

Now if ChoixPortCom is null it will throw a NullPointer because you are trying to invoke a method (equals) on a null reference.

And something I like to think of as a best practice is to always use brackets:

if (ChoixPortCom == null) {
    JOptionPane.showMessageDialog(null, "Choose Port COM");
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top