java for loop that runs list executes only once - java

The for loop in the code below only executes once. I was looking at similiar questions but those have something that breaks it like editing the list in the loop while I dont.
public String getProfileList(JSONObject obj, String uuid) {
JSONObject profile = (JSONObject) obj.get("profiles");
#SuppressWarnings("unchecked")
ArrayList<String> list = new ArrayList<String>(profile.keySet());
System.out.println(list);
for (String object: list) {
System.out.println(object);
String isUUID = (String) ((JSONObject) profile.get(object)).get("mpm-data:uuid");
System.out.println(object + " == " + isUUID);
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}
}
System.out.println("no profile found.");
return null;
}
This code outputs this:
[5fb4acd48e7d422eabecd82e32fb03c6, 44d01181eae635d31f2cefe5e1f75cd4,e0e96e422659dfdc1ad16d53a37ee618, a3ae7136f900457290e99bd657db0385]
5fb4acd48e7d422eabecd82e32fb03c6
5fb4acd48e7d422eabecd82e32fb03c6 == null

For your console output you can see that isUUID is null. This means that when you attempt to call its method equals there is actually no object to call it to and you should be getting a NullPointerException. That's why it is best to do equals assertions with the part you know will not be null on the left side:
uuid.equals(isUUID) would be better.
Notice that if you do an equals assertion with a variable and a static string then it is best to do it like so:
"myCompareString".equals(myVariable), since "myCompareString" can never be null whereas myVariable can.

if (isUUID.equals(uuid)) will throw a nullPointerException when isuuid is null.
You should check if the data is right, and handle the exception.
And you can use StringUtils.equals(String str1, String str2) in commons-lang.jar, then you don't need to handle the null yourself, see http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html

System.out.println(object + " == " + isUUID);
Code prints
5fb4acd48e7d422eabecd82e32fb03c6 == null and next statement you are using in if condition .If isUUID is null it should throw null pointer exception.Can you please check this point
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}

Related

Java if condition for empty validations

I'm new to java and i want to do a condition check and return a message
PersonalDetails Request: It holds the value for all the below infos
getID();
getName();
getDesignation();
getHomeAddress();
getOfficeAddress();
getEmailID();
getMobile();
getHomePhone();
getOfficePhone();
i want to check all values for empty then return message.
Like "Your ID,Name, Mobile cannot be empty" if i pass empty values to ID, Name, Mobile
Below is the sample snippet which has to do the check for all PersonalDetails Request
public static String checkValue(PersonalDetails Request) {
String str="Your ";
if(request.getID().isEmpty())
{
str="ID,";
}
if(request.getName().isEmpty())
{
str="Name";
}
if(request.getDesignation().isEmpty())
{
str="Designation";
}
if(request.HomeAddress.isEmpty())
{
str="Address";
}
str+= "cannot be empty"
return str;
}
Is this right or any other easy approach will address the issue
Thanks in advance
No if the string contains null then it will through a null pointer exception.
You first need to check it for null then for Empty.
Can we rely on String.isEmpty for checking null condition on a String in Java?
There are multiple suggestions for your code:
Use camel-case for variables, methods etc. in your code. For example parameter should be named as PersonalDetails request and not PersonalDetails Request. These are standard coding conventions. Also getter/setter should follow the rules, check HomeAddress which seems to miss it.
Use StringBuilder class as it performs better specially in case of appending while in a loop.
You need to check for null before performing any operation else you will be facing a NullPointerException. You can also read about Optional in Java 8.
The code can be improved like:
public static String checkValue(PersonalDetails request) {
if(null == request ) {
//Throw exception or log/return message as per your need.
}
int some_appropriate_size = 50; // You need to decide about some_appropriate_size so that it starts with enough capacity for the full content we are going to append.
StringBuilder stringBuilder = new StringBuilder(some_appropriate_size);
stringBuilder.append("Your ");
if(null!= request.getID() && request.getID().isEmpty())
{
stringBuilder.append("ID,");
}
if(null!= request.getName() && request.getName().isEmpty())
{
stringBuilder.append("Name");
}
if(null!= request.getDesignation() &&request.getDesignation().isEmpty())
{
stringBuilder.append("Designation");
}
if(null!= request.getHomeAddress() && request.getHomeAddress().isEmpty())
{
stringBuilder.append("Address");
}
stringBuilder.append( "cannot be empty");
return stringBuilder.toString();
}
Your condition is correct but you forget to concat string in each if. If don't concate it will not have existing value but new value only.
public static String checkValue(PersonalDetails Request) {
String str="Your ";
if(request.getID().isEmpty())
{
str= str + "ID,";
}
if(request.getName().isEmpty())
{
str= str + "Name";
}
if(request.getDesignation().isEmpty())
{
str= str + "Designation";
}
if(request.HomeAddress.isEmpty())
{
str= str + "Address";
}
str+= "cannot be empty"
return str;
}
My suggestion will be to use StringBuilder to get better performance.
Here it's better to check not only isEmpty. It's better to check null, " " or "-" as well.
Before you check isEmpty or "-" or " ", make sure to check null to avoid getting NullPointerException

My method keeps saying I need to return a string but my method has a return statement that returns a string

I have a method that is suppose to go get a JSON object that has all the champion ids from league of legends and I want it to return the name of the champion based on the "number" that is passed to the method from another loop in the program.
public String getChampionName(int number) //where it is saying its not returning a string
{
try
{
String JSonChampionName = readURL("myURLwithAPIkey");
JSONObject object = JSONObject.fromObject(JSonChampionName);
JSONObject championData = (JSONObject)(object.get("data"));
JSONObject champName = (JSONObject)(championData.get(number));
if(object != null && championData != null && champName != null)
{
String cName = champName.get("name").toString();
return cName;
}
else
return "";
}catch(Exception v){}
}
Any ideas I am just not sure why its telling me the method is not returning a string.
What if there is an Exception caught? In that case your method doesn't have a return statement.
Either don't catch the Exception, or provide a return statement in the case that the Exception is caught.
The compiler is saying you need to return a string on every possible path that the program could take. If an exception occurs, you will catch it, but your catch block will do nothing; then the program will fall to the end of the method without returning anything.
You need to fix your method so that if an exception is caught, you either return something, or throw some other exception.
You would need to return the type expected in all scenarios!! Thats what compiler expects.
Right now , with the code that you implemented , the problem is that in case of an exception this method does not return anything...
Thats why compiler is complaining even though you have a return statement..

compare an integer to a null value

I need to see if a text field has an empty value. I need to see if
if(Double.parseDouble(distanceTf.getText())==0)
I know 0 won't work. I also know null won't work and I know .equals won't work.
Does anyone know how I can compare this line of code to a null value?
if (stageTf.getText().equals("") || Double.parseDouble(distanceTf.getText()) == null) {
JOptionPane.showMessageDialog(null, "You did not enter both a stage number and distance");
return;
}
Thanks for all the above replies but they don't work.
The part of the code I have trouble with is:
if (Double.parseDouble(distanceTf.getText())==null)
The rest of it is fine.
I have tried putting this outside the if statement and using distanceTf.getText().equals("")
in the if statement but this doesn't work either.
I just can't find out how to assign an empty value to the line of code for a double.
I know null, .equals or "" won't work.
You're not clear on which value could be null, so I'll assume both.
Since Double.parseDouble requires a non-null argument, you need to check it for null.
if(null != distanceTf.getText() && Double.parseDouble(distanceTf.getText()) != 0.0)
stageTf.getText() could return null too, but if you're guaranteed to be comparing a known non-null String against null, it would return false. So, this comparison is safer:
if("".equals(stageTf.getText())
The important thing to understand is: what you mean with null value? A null reference or an empty string?
You could do
stageTf.getText().isEmpty()
to check if the string is empty and parse it only if it contains something.
// here remember it's still wrong
if (!stageTf.getText().isEmpty() && Double.parseDouble(distanceTf.getText()) == null) {
Second problem: Double.parseDouble doesn't return null since it returns a native type.. it thrown an exception if something went wrong. So you can catch NumberFormatException.
Then you could write:
try {
double result;
if (!stageTf.getText().isEmpty() && (result = Double.parseDouble(distanceTf.getText()))) {
/* i think you need the result of the conversion, so i saved it in result */
}
}
catch (NumberFormatException e) { /* something went wrong! */ }
You need to test if the field is empty first. You did it correctly with your first conditional on the stageTf field. You need to do the same with the distanceTF field. This means nesting your conditional statements.
if(stageTF.getText().equals(""))
if(distanceTF.getText().equals("")){
/* ... */
} else {
//here it is safe to test for exceptions by using a try/catch
try{
//here you can parse the string to your Double
}catch(NumberFormatException nfe){ /* ... */ }
}
first of all you should check for null before empty because if the value is null you'll get a NullPointerException on the first one.
Second you'll get a NullPointerException if distanceTf.getText() is null on the Double.parseDouble
Double.parseDouble() doc
what I would do is create a method validate as follows:
private boolean validate(String field){ //where field = stageIf.getText() for example
if(field != null && field.trim().length() > 0)
return true;
else return false;
}
Parse outside if statment, then just compare :
if(distanceTf.getText() == "")

How to check null on StringBuilder?

I want to check for null or empty specifically in my code. Does empty and null are same for StringBuilder in Java?
For example:
StringBuilder state = new StringBuilder();
StringBuilder err= new StringBuilder();
success = executeCommand(cmd, state, err);
/* here executeCommand() returns empty or null in state, I cant make changes in <br/> executeCommand() so can I check it in my code somehow for state, if its null or empty? */<br/>
if (state == null) { //do blabla1 }
if (state.tostring().equals("")) { //do blabla2 }
Does above code make sense or how should I change it?
No, null and empty are different for StringBuilder.
StringBuilder nullBuilder = null;
if(nullBuilder == null) {
System.out.println("Builder is null");
}
&
StringBuilder emptyBuilder = new StringBuilder("");
if(emptyBuilder == null || emptyBuilder.toString().equals("")) {
System.out.println("Builder is empty");
}
In Java, null is a reference literal. If a variable is null then is not referring to anything.
So, if you have StringBuilder s = null, that means that s is of type StringBuilder but it is not referring to a StringBuilder instance.
If you have a non-null reference then you are free to call methods on the referred object. In the StringBuilder class, one such method is length(). In fact if you were to call length() using a null reference then the Java runtime will throw a NullPointerException.
Hence, this code is quite common:
If (s == null || s.length() == 0/*empty if the length is zero*/){
// do something
It relies on the fact that evaluation of || is from left to right and stops once it reaches the first true condition.
Null mean, there are no object in the heap for that reference variable. This is common to all java object, not specific to StringBuilder and Empty means, "".
In your code, you have created a StringBuilder object, so checking null is redundant. And, You can check empty by using isEmpty() method in from java String api
if(state.tostring().isEmpty()) {
//
}
And checking null is correct. Find the corrected version here
if (state == null) {
// ...bla 1
} else if (state.tostring().isEmpty()) {
//... bla 2
}
Your second if condition will throw NullPointerException, if the state is null. So if should be nested with if else
No. empty means, that there are no characters in the StringBuilder. null means that there is no StringBuilder object at all.
A variable is only null if it has a reference type (for example String, StringBuilder, Set, as a thumbrule: all capitalized types) and it is not initialised yet or has been set explicitly to null.
The below code may help you,
StringBuffer sb = new StringBuffer();
String str = sb.toString();
if(!"".equals(str)) {
System.out.println("String : " + str);
} else {
System.out.println("Empty Builder");
}
You can try like this
StringBuilder state = new StringBuilder();
if(StringUtils.isNotBlank(state .toString())){
//this will check for null, " ", ""
}

How to handle null in Pattern.compile?

How to handle null when using Pattern.compile? I'm using the following line to compare strings:
Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()
There are some cases where s1 can be null and obviously it throws NullPointerException. I know this could be handled by another if condition to s1, but I would like to know is there's an alternate solution.
EDIT
Iterator iter = sampleList().iterator();
while (iter.hasNext()) {
SampleObj so = (SampleObj) iter.next();
if (!s1.equalsIgnoreCase("")) {
if (Pattern.compile(Pattern.quote(s1), Pattern.CASE_INSENSITIVE).matcher(so.getS1()).find())
match = true;
else
match = false;
}
if (!s3.equalsIgnoreCase("")) {
if (Pattern.compile(Pattern.quote(s3), Pattern.CASE_INSENSITIVE).matcher(so.getS3()).find())
match = true;
else
match = false;
}
}
s1 and s3 are inputs which are matched over iterator.
You have to check for null; e.g.,
if(s1 != null && Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()))
Pattern.matcher() will always throw a NullPointerException when you pass in null, so: no, there is no other way, you'll have to check for null explicitly.
I use
String.valueOf(s1)
which results in having "null" instead of null.

Categories

Resources