.substring() throws a nullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am creating a Chess program on NetBeans using jButtons as squares, and my java knowledge is limited to what I have learnt at school.
So this line
int verticalValue = Integer.parseInt(newButton.substring(1,1));
returns a nullPointerException and I can't figure it out whatsoever. Here is the relevant code:
static void pawnMovement(JButton but){
String buttonName = but.getName();
String newButton = buttonName;
int verticalValue = Integer.parseInt(newButton.substring(1,1));
The names of all buttons are in the format letterNumber, so I don't see why this shouldn't work.
Thanks!

This code should produce a NumberFormatException as the string from substring(1, 1) will always be empty, unless newButton is null because it hasn't been set.
I would check in your debugger that is has been set. I would also ensure you are trying to parse at least 1 character.

When you do a new JButton("name") - it sets the variable JButton.text as name. Hence, but.getText() should work for you.
In your case, but.getName() returns NULL because you have NOT done but.setName() first. but.setName() is required for but.getName() to work.
Hence, buttonName & newButton are NULL.
Hence, when you do newButton.substring(1,1) - it causes NPE because newButton is NULL

Related

Android: java.lang.IllegalArgumentException: Unknown color error [duplicate]

This question already has answers here:
CardView setCardBackgroundColor won't work
(4 answers)
Closed 2 years ago.
When I try building a project, an error appears, indicated in the name of the topic. directs here:
if (arrList[position].color != null){
holder.itemView.cardView.setCardBackgroundColor(Color.parseColor(arrList[position].color))
}else{
holder.itemView.cardView.setCardBackgroundColor(Color.parseColor(R.color.ColorLightBlack.toString()))
}
if I remove the condition that is written in "else", the project starts without errors. Tried changing the color, nothing changed!
From this post we can see that you should write
holder.itemView.cardView
.setCardBackgroundColor(ContextCompat.getColor(getActivity(), R.color.ColorLightBlack))
You are trying to use parseColor, which takes a hexadecimal string as an argument. But calling toString() probably isn't making the conversion to hexadecimal.
R.color.ColorLightBlack is an integer value assigned by the Android System. You are trying to pass this value to parseColor method which required String. Even if you use toString on R.color.ColorLightBlack, the value still remains Integer, hence you are getting the error.
You can update the code like this:
if (arrList[position].color != null){
holder.itemView.cardView.setCardBackgroundColor(Color.parseColor(arrList[position].color)) }
else {
holder.itemView.cardView.setCardBackgroundColor(R.color.ColorLightBlack))
}

Java if statment ending with a semi-colim [duplicate]

This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 3 years ago.
I have encountered the following strange behavior in Java using jdk 13.0:
String foo = "Something";
String bar = "Other";
if (foo.equals(bar));
{
System.out.println("Face palm");
}
Sadly, the above comparison succeeds and the "Face palm" is printed out.
What causes this behavior is the existence of the semi-colon in the end of the if statement.
The correct way of doing this is:
String foo = "Something";
String bar = "Other";
if (foo.equals(bar))
{
System.out.println("Face palm");
}
Could anyone explain why Java behaves like this ?
Could that be just an uncaught syntax error by the compiler ?
It does not mean that comparison succeeds - basically you just created if statement with empty body and then opened the local anonymous code block (starting from {)
The Face palm value in this case will be printed out always - no matter what the condition result will be
Read more here:
Semicolon at end of 'if' statement
Anonymous code blocks in Java

.equals() method not working with multi dimensional arrays [duplicate]

This question already has answers here:
Error while using .equals() method on multi dimensional array java [duplicate]
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
System.out.print("Enter the Item number of what is to be changed");
String itemNO = in.next();
for (int i = 0; i<NewItem.itemArray.length; i++)
{
String value = NewItem.itemArray[i][3];
if(value.equals(itemNO))
{
//Rest of the code here
}
}
When running the program, it throws an exception at "if(value.equals(itemNO))". This is the error it shows.
Exception in thread "main" java.lang.NullPointerException
at DeleteItem.deleteItem(DeleteItem.java:34)
at EditItemDetails.editItem(EditItemDetails.java:25)
at CD_Universe.editItemDetailsActions(CD_Universe.java:84)
at CD_Universe.main(CD_Universe.java:109)
value can still be null in your code, and therefore attempting to invoke equals() on it will throw an exception. Just because you are able to iterate over given element does not mean it has been initialized. I assume you have created an array of given size, but certain elements of that array have never been assigned a value.
You may fix this by populating the elements or adding a null check: if (value != null)...
In Java, only arrays of primitives are initialized with default values (since primitive type cannot be null. Arrays of reference types will not have their values initialized.

How to make sure that values written in a textfield are the same using a simple loop function? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I wrote a simple code just to check the values between textfields and compared whether they are the same or not. I want them to be the same, if not it will produce an error. It's about rewriting an email.
String a = studentemail.getText();
String b = rewritestudentemail.getText();
if(a != b){
JOptionPane.showMessageDialog( null, "Student Email rewritten incorrectly.","Error!",JOptionPane.OK_OPTION);
}
The program persists that there is an error even though I indicated the same string values in both of the fields. Why's that?
Change your conditional to be this:
if(!a.equals(b))
{
JOptionPane.showMessageDialog( null, "Student Email rewritten
incorrectly.","Error!",JOptionPane.OK_OPTION);
}
Make sure you have the ! before a.equals(b)) since you only want the error to appear when they are not equal.
rather layout your logic like this:
if (!a.equals(b)){
//JoptionPane...
}
In java two strings are compared by using the ".equals()" function.
Try:
if (!a.equals(b)) {
...

Java - NullPointerException in Array [duplicate]

This question already has answers here:
NullPointerException when Creating an Array of objects [duplicate]
(9 answers)
Closed 9 months ago.
I have encountered the following problem: I have a java class with a private member like so:
private Arcs[] arcs;
This is not initialised in the constructor because I don't know the length of my vector yet, but it is initialised in the read function, where I read the info from a file.
In this function I do the following:
arcs = new Arcs[n]; //n is a number read from file
Then there is a while cycle in which I read other stuff from the file and I have something like:
while(condition){
...
arcs[i].add(blah); //i is a valid number, smaller than n, and the add function is also correct
...
}
But here I have an error saying NullPointerException and I don't understand why. I would appreciate it, if someone would explain to me what's happening.
Are you actually ever storing an Arcs object in arcs[i]? If not, all elements of arcs[] will be initialized to null. (Hence the NPE)
Do something like this:
while(condition){
// ...
arcs[i] = new Arcs();
arcs[i].add(blah);
// ...
}
Reference:
Java Tutorial: Arrays

Categories