NullPointerException despite specifying [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I want to code a personal modloader for minecraft (create files , download files, sort files, etc) and the first window which is created is a JOptionPane which asks for a Version (i do not code in java really long, i don´t use spinner, just a "msg dialog" asking for a version). The code is:
public JOptionPane version = new JOptionPane();
public String modversion;
public Version()
{
showVersion();
}
public static void main(String[] args)
{
}
public void showVersion()
{
//input = version
String vers = version.showInputDialog("Welche Version soll modifiziert werden?");
if (vers.equals(null)) {
return;
} else {
if(vers.equals("1.5.2") || vers.equals("1.6.2") || vers.equals("1.6.4") || vers.equals("1.7.2") || vers.equals("1.7.10") || vers.equals("1.8") || vers.equals("1.8.9") || vers.equals("1.9") || vers.equals("1.10.2") || vers.equals("1.11.2"))
{
//mod version is saved as String (title for the config list)
modversion = vers;
return;
} else {
// with incompatible input the method will be repeated
JOptionPane.showMessageDialog(null, "Diese Version wird leider nicht supportet");
showVersion();
}
}
}
If you just press "Ok", the input would equal "null":
if (vers.equals(null)) {
return;
}
but it don´t quit the method, it says NullPointerException. Why doesn´t it just quit the method?

It's correct that you get an exception here.
Here:
if (vers.equals(null)) {
You are trying to call a method on a variable that is null. As you said yourself, vers is null at this point.
To check for null you have to use the == operator.
if(vers == null) { return;}

You can't call .equals() on a null object.
To check if the vers variable is null, you should use vers == null

Related

JUnit java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Im new to software testing, i keep getting java.lang.NullPointerException for some reason and i don't know what it is
This is what i am testing on
public int getNumberOfStudents()
{
int validStudents = 0;
int i = 0;
boolean done = false;
do {
if (students[i] != null && students[i].exists())
validStudents++;
else
done = true;
i++;
} while(i < students.length && !done);
return validStudents;
} // end of getNumberOfStudents
This is the test case
class Testing {
RegistrationSystem GNS = new RegistrationSystem();
#Test
//#SpiraTestCase(testCaseId=5487)
public void test() {
assertEquals("validStudents", GNS.getNumberOfStudents());
}
}
I guess at line if (students[i] != null && students[i].exists()) you have not initialized students while creating RegistrationSystem Object, create it and it will work also I can see a problem in assert that you are comparing string with int :)assertEquals("validStudents", GNS.getNumberOfStudents());
Where exactly are you getting error.
One problem with your test case is you are comparing string "validstudents" with integer returned from function GNS.getNumberOfStudents(). You need to set a number of students, then call getNumberOfStudents() assert it with the expected value.

Check if string contains an # symbol or if the string is null [duplicate]

This question already has answers here:
How can I check if a single character appears in a string?
(16 answers)
Closed 4 years ago.
Basically, I have a form where people can enter stuff in, and there is one part where they input an email address. Sometimes, people just put in their name and don't put an actual email address. Sometimes they do not fill it out at all.
Is there any easy way to check to see if the string has an # symbol in it and check to see if its Null?
Any help is appreciated
Use an AND boolean operator. str != null && str.contains("#")
We first check the string is not null, then check that it contains '#'. Note: The reason that the null check is first is so that we do not attempt to access the string if it is null.
String s = "email#email.it";
if(s!= null && !s.isEmpty() && s.contains("#") ) {
System.out.println("ok");
}
else System.out.println("ko");
}
The String class contains a contains method to check the # symbol, and you can simply check for null with a != null call:
public static void main(String[] args) {
String a = "should be false";
String b = "should be #true";
String c = null;
System.out.println(checkString(a));
System.out.println(checkString(b));
System.out.println(checkString(c));
}
static boolean checkString(String str) {
return str != null && str.contains("#");
}
Output:
false
true
false
Here is some really simple code to achieve this:
String ourString = "example#emailIsCool.com";
if(/* Check if our string is null: */ ourString != null &&
/* Check if our string is empty: */ !ourString.isEmpty() &&
/* Check if our string contains "#": */ ourString.contains("#")) {
System.out.println("String Fits the Requirements");
} else {
System.out.println("String Does Not Fit the Requirements");
}
For future reference, this is extremely broad for Stack Overflow, and you should try checking the javadoc before you make a post asking for the answer. For example, here is the javadoc for the String class: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Javadocs provided by Oracle detail every method and attribute for all of the classes included in the standard java library. Here is a link to the javadoc homepage for Java 7.
https://docs.oracle.com/javase/7/docs/api/overview-summary.html
I think use Optional is the best way to do this.
Codes like this:
String nullEmail = null;
System.out.println(Optional.ofNullable(nullEmail).filter(s -> s.contains("#")).isPresent());
String rightEmail = "478309639#11.com";
System.out.println(Optional.ofNullable(rightEmail).filter(s -> s.contains("#")).isPresent());
String wrongEmail = "chentong";
System.out.println(Optional.ofNullable(wrongEmail).filter(s -> s.contains("#")).isPresent());
The output is:
false
true
false

how to check jTable nullpointer in row [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
how to check my jtable if null pointer?
my code is always null pointer and then can't export to xls.
this my code
if (tbGudangSales.getValueAt(i, 5).toString().trim().length() == 0) {
status = "tidak ada penjualan";
} else{
status = tbGudangSales.getValueAt(i, 5).toString();
}
label = new Label(4, baris, status, bordertabel);
excelSheet.addCell(label);
this my error
this my value table
All you need to do is to check if the value is null. For example:
Object value = tbGudangSales.getValueAt(i, 5);
if (value != null)
{
if(value.toString().trim().isEmpty()) // instead checking the length "manually", you can use the isEmpty() method
{
status = "tidak ada penjualan";
}
else
{
status = value.toString();
}
}

AVL TREE REBALNCE [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
in Line 7 i get nullpointerexception, how can i fix that ? any ideas?
private void updateHeights(BSTreeNode v) {
BSTreeNode u = v;
while (u != null) {
int bfc=updateNodeHeight(u);
u = u.parent;
if (bfc<=-2) {
if( getHeight(u.left.left) >= getHeight(u.left.right) ) { // Null Pointer Exception
u = rotateRight(u);
} else {
u=LR(u);
}
}
}
}
There are two possibel problems, and as many solutions. First is placing a null check in getHeight() which I assume has been done based on your programming style (the check in while conditional). That leaves a possible null pointer issue with u.left. As such:
Ensure u.left is not null, like this:
getHeight(u.left != null && ((u.left.left)>=getHeight(u.left.right))

How avoid multiple IF loops in Java [duplicate]

This question already has answers here:
Avoiding NullPointerException in Java
(66 answers)
Closed 9 years ago.
What is the best way to avoid multiple if blocks which is used for null checks in Java?
The following is my sample code. Which one is the most optimized way?
if (address!=null} {
if (firstName!=null) {
if (lastName!=null) {
}
}
}
Use &&. && is logical and. && combines two values and returns a boolean which is true if and only if both of its operands are true
if(address!=null && firstName!=null && lastName!=null)
{
}
For instance
boolean b;
b = 3 > 2 && 5 < 7; // b is true
b = 2 > 3 && 5 < 7; // b is now false
if loop is a wrong word. You should say if statements As in you case you can use OR (||) or AND (&&)statement like this
if(address!=null && firstName!=null && lastName!=null)
{
}
Try AND(&&) if you want to pass all checks or intead of nested if statements and try OR(||) for non nested like else if or simply say if you want to pass anyone of your condition But
if all of these are Strings then you should try like this
"yourValue".equals(stringValue)This will skip the null check.
Use and operator (&&)
if(address!=null && firstName!=null && lastName!=null)
{
//DoSomething here
}
And I suggest you to see Short circuit evaluation
there are no if LOOPS
boolean complete = address != null && firstName != null && lastName != null;
if (complete)
{
}
What about:
public boolean notNulls(Object ... args) {
for(Object arg : args)
if (arg == null) return false;
return true;
}
Use:
if (notNulls(address, firstName, lastName)) {
// do something
}
As others point out, a logical and (&&) is probably the best way to consolidate your logic. An && operation will only evaluate to true if both sides evaluate to true.
if (address != null && firstName != null && lastName != null) {
// Whatever you want to do with that...
} else {
// Whatever you want to do with bad input
}
For the sake of diversity, you could also use a try-catch approach. In Java, a NullPointerException will be thrown if you try to call a method on a null value, which you can catch and handle.
try {
// Whatever you want to do with that...
} catch (NullPointerException npe) {
// Whatever you want to do with bad input
}
This approach can be helpful if you've got a really big set of inputs that might be null, although in general I wouldn't advocate it. (The problem with the second approach is that if you call some other method from the try part that triggers a NullPointerException, it will end up in the catch block here, even though it may be totally unrelated to these inputs - i.e. you could make it hard for yourself to spot a bug in a different part of your program.)

Categories