I am writing a method which contains if else statements, but also a return keyword. Now, I'm writing something like this:
public boolean deleteAnimal(String name) throws Exception{
if(name == null || name.trim().isEmpty())
throw new Exception("The key is empty");
else if(exists(name)){
hTable.remove(name);
}
else throw new Exception("Animal doesn't exist");
return hTable.get(name) == null;
}
I'm new in java and this is my first time trying to learn a programming language. I read that the 'else' statement excecutes always if the if condition is false.
Now, if these are false:
if(name == null || name.trim().isEmpty())
throw new Exception("The key is empty");
else if(exists(name)){
hTable.remove(name);
}
Shouldn't the else part always excecute?
else throw new Exception("Animal doesn't exist");
I noticed this since this method is returning true/false, and it seems like it's ignoring the else part, even when the conditions above it are false.
Without the knowledge about the rest of the code exists(String name) and the type of hTable (Map<String,? extends Object>) I need to guess:
If exits returns true, the else if statement evaluates to true. The line hTable.remove(name) will be executed. The else-branch is not invoked, because the else if was. Now the last line will return hTable.get(name) == null;
I think it will return true, because the hTable will return null.
I'll try to add comments to your snippet to help you understand the flow:
public boolean deleteAnimal(String name) throws Exception{
if(name == null || name.trim().isEmpty())
throw new Exception("The key is empty"); //Executes if 'name' is null or empty
else if(exists(name)){
hTable.remove(name); // Excecutes if 'name' is not null and not empty and the exists() returns true
}
else
throw new Exception("Animal doesn't exist"); //Excecutes if 'name' is not null and not empty and the exists() returns false
return hTable.get(name) == null; //The only instance when this is possible is when the 'else if' part was executed
}
Hope the comments helps you understand the flow!
With this in mind, the answer to your question is 'yes'.
Related
I am fetching value from db in dbval variable. So I want to add condition, pass the case if the value equals "apple" or the value is empty or null. But if the value is diff like "orange" or "mango", throw error.
My code:
if (StringUtils.equals(apple, dbval) || dbval.equalsIgnoreCase(null) || dbval.isEmpty())
{
dbValueFlag = true;
logger.info("DB value matched ",);
}
else
{
logger.info("DB valuenot matched for pnac");
}
You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.
Example:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Or
if(str != null && !str.isEmpty()) { /* do your stuffs here */ }
Add throws InvalidArgumentException to your method signature. And throw this exception from the else block in your code.
public void thisIsYourMethod(String dbVal) throws InvalidArgumentException {
if (StringUtils.equals(apple, dbval) || dbval.equalsIgnoreCase(null) || dbval.isEmpty()) {
dbValueFlag = true;
logger.info("DB value matched ",);
} else {
logger.info("DB valuenot matched for pnac");
throw new InvalidArgumentException("Argument Passed in Wrong");
}
}
The following Java snippet of code confuses me a bit. The method is trying to check whether two objects are NOT equal, using the standard .equals() method to denote that they are equal. Additionally, a boolean can determine whether two null's are considered equal or not. I'm wondering if:
The boolean logic in this method is indeed correct?
the return statement in the middle block can be omitted somehow. Could this logic be rewritten in a more concise or other way, maybe dropping the empty return, but keeping a high level of human readability of the code?
Snippet:
public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual)
{
if(considerBothNullAsEqual && variable == null && otherVariable == null)
{
throw new Exception("not allowed to be equal");
}
if(variable == null || otherVariable == null)
{
return;
}
if(variable.equals(otherVariable))
{
throw new Exception("not allowed to be equal");
}
}
Yes, the logic in the method is correct. It throws the exception if the two objects are equal. You could remove the second condition and combine it with the third one, but I don't see much point. If you did, the method might look like this.
public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual) throws Exception
{
if(considerBothNullAsEqual && variable == null && otherVariable == null)
{
throw new Exception("not allowed to be equal");
}
if(variable != null && variable.equals(otherVariable))
{
throw new Exception("not allowed to be equal");
}
}
Note that there's no need to check whether otherVariable is null separately, since the equals method on variable should return false if otherVariable is null.
There's an even more concise way to write this, but it's not worth considering, since it sacrifices readability.
I am getting the error The method parseInt(String) in the type Integer is not applicable for the arguments (boolean)
Here is the code
} else if (Integer.parseInt(answerField.getText() == null)) {
JOptionPane.showMessageDialog(null, "You did not enter an answer!");
}
I have also tried this but it doesn't work:
(Integer.parseInt(answerField.getText().equals("")))
&
(Integer.parseInt(answerField.getText().length()) == 0)
I just want to check to see if nothing has been entered and if so display a JOptionPane.
Edit: The var answerField is a JTextField, where the user inputs an answer of a mathematical question. So the ActionListener then determines if the answer is correct, hence the parseInt (because of it being a mathematical operation)
do {
checkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Integer.parseInt(answerField.getText()) == correctAnswer) {
count++;
JOptionPane.showMessageDialog(null, "Correct");
} else if (Integer.parseInt(answerField.getText().length()) == 0) {
JOptionPane.showMessageDialog(null, "You did not enter an answer!");
} else {
count++;
JOptionPane.showMessageDialog(null, "Incorrect!");
System.exit(0);
}
}
});
} while (count < 11);
Lets analise the code you have
(Integer.parseInt(answerField.getText() == null))
the parameter
answerField.getText() == null
return a boolean and the method Integer.parseInt(bool) is not defined in the Integer class.
It looks like you want to do:
else if (someConditionHere) {
Integer.parseInt(answerField.getText());
JOptionPane.showMessageDialog(null, "You did not enter an answer!");
}
all of the values inside of your parse int method return a boolean becuase they are performing a comparison between two values that result in either true or false. You should use Boolean.parseBoolean() to return either "true" or "false" strings
Integer.parseInt(answerField.getText() == null) is evaluated as
Integer.parseInt("someTextext" == null) then
Integer.parseInt(true/false)
Try to parse a boolean as an Integer will result as an error
To check is your field is null, only do if(answerField.getText() == null)
then if is not null you can try to parse the field value to an Integer the way you did.
I am not sure why you want to call Integer.parseInt, because you already have a boolean expression in your condition:
} else if (answerField.getText() == null) {
JOptionPane.showMessageDialog(null, "You did not enter an answer!");
}
Note that if conditions in Java can only accept boolean expressions, and you couldn't pass in an integer or whatever else you'd think of as truthy or falsy (unlike C or Javascript, for example).
If all you want to do is check to see if there's some string contained in answerField, then all you need to do is check to see if it's not null or empty.
if(!("".equals(answerField.getText()) || null == answerField.getText()) {
// other, non-integer-handling code here
}
You do not want to handle parsing the integer if there's an empty string or if it's null, since that could result in a NullPointerException.
My goal in the below code is to check for input that is longer than two places after the decimal point, then throw an exception. I cant seem to get it correct though. I am trying to use indexOf to get to the decimal point and then I want to check the length of the portion after it. If it is greater than 2 I want it to throw the exception. Anybody have some tips for this situation?
public ChangeJar(final String amount) {
int i = amount.indexOf('.');
String temp = amount.substring(i + 2);
if(temp.length() > 2 ){
throw new IllegalArgumentException("Too many decimal places!");
}
if (amount == null || Double.parseDouble(amount) < 0) {
throw new IllegalArgumentException("amount cannot be null!");
}
double amt;
try {
amt = Double.parseDouble(amount);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Invalid entry. Format is 0.00.");
}
amountHelper(amt);
}
I also wanted to know how I could add error checking to this constructor as I dont want null inputs. I get an error when trying to add error checking that says the constructor call must be the first statement in the method.My code for the constructor is:
public ChangeJar(final ChangeJar other){
if(other == null){
throw new IllegalArgumentException("Values cannot be null!");
}
this(other.quarters, other.dimes, other.nickels, other.pennies);
}
All suggestions are appreciated!
As Java does not allow to put any statements before the super or constructor calls in a constructor. Hence you cant do this:
public ChangeJar(final ChangeJar other){
if(other == null){
throw new IllegalArgumentException("Values cannot be null!");
}
this(other.quarters, other.dimes, other.nickels, other.pennies);
}
You may add the check in the constructor that you are calling.
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() == "")