Boolean If statement only returning outside [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public static boolean stringToBoolean (String horv) {
if (horv == "H") {
return true;
} if (horv == "V") {
return false;
} else {
return true;
}
This is a small part of a program I am creating. The program is reading from a file and inputting the data into an array. For this part it is reading what will either be a "H" or "V" from the file and converting it to a boolean value. The problem is when I run the program I am only getting true for every value, even the ones that have a "V" as their variable.

Change the code to be:
if ("H".equals(horv)) { return true; }
...

Try This
public static boolean stringToBoolean (String horv) {
if ("H".equals(horv)) { // use equals method for string comparison
return true;
} if ("V".equals(horv)) {
return false;
} else {
return true;
}

String variables should be compared with equals() method in java.

In Java you have compare String with a method equals() Like this
public static boolean stringToBoolean (String horv) {
if (horv.equals("H")) return true;
if (horv.equals("V")) return false;
return true;
}

Related

Java - make boolean isHigherGeneration () metod return YES/NO

I am having a little trouble with my homework. I have to have a boolean isHigherGeneration() method that compares 2 CPU objects based on their generation. I was able to make my code compare the 2 objects, but I need the result to return YES/NO instead of true/false. I tried creating a string and transforming it into a boolean, but it didn't work. Can someone help me please? Here is my code:
public boolean isHigherGeneration(CPU cpu){
String YES = "YES";
String NO = "NO";
boolean t = Boolean.valueOf(YES);
boolean n = Boolean.valueOf(NO);
if (this.generation > cpu.generation)
return t ;
else
return n;
}
Thank you in advance for your help :)
It sounds from the question like it doesn't want you to return a boolean, but a String with either the value YES or the value NO instead of a boolean, so what you need to do is translate the result of the boolean expression into a String with the value YES or the value NO.
Thus, in this case, there's no need to play around with boolean in your code. You can compare the CPU generation and just return YES if the value is true and NO if the value is false:
public String isHigherGeneration(CPU cpu) {
if (generation > cpu.generation) {
return "YES";
} else {
return "NO";
}
}
Edit: From the sounds of the requirements, you need a boolean method that returns String, which is impossible. (That's like saying you want to buy an apple but end up with a pear.) If you do need a String result and a boolean method, you could divide them into three like this:
// Boolean method
public boolean isHigherGeneration(CPU cpu) {
return generation > cpu.generation;
}
// String method
public String toYesNo(boolean result) {
if (result) {
return "YES";
} else {
return "NO";
}
}
// Converter
public String isHigherGenerationYesNo(CPU cpu) {
return toYesNo(isHigherGeneration(cpu));
}
but this just all seems silly. I think maybe we're having a misunderstanding in the question. Could you post the question verbatim so that we can ensure that we've understood it correctly?
If you want to return "YES" or "NO", the return type of the method must be a String:
public String isHigherGeneration(CPU cpu) {
if (this.generation > cpu.generation)
return "YES";
else
return "NO";
}
or
public String isHigherGeneration(CPU cpu) {
return this.generation > cpu.generation ? "YES" : "NO";
}

How to compare two Booleans in Java? [duplicate]

This question already has answers here:
Compare two objects with a check for null
(7 answers)
Closed 5 years ago.
I have to compare two Boolean wrappers with each other. As a result I want to know if they are equal or not.
This is what I came up with:
public static boolean areEqual(final Boolean a, final Boolean b) {
if (a == b) {
return true;
}
if (a != null && b != null) {
return a.booleanValue() == b.booleanValue();
}
return false;
}
Is there a better and/or shorter way to correctly compare two Boolean wrappers for equality?
First I wanted to use Object.equals() or Boolean.compareTo() but both ways could end up in a NullPointerException, right?
Maybe there is something that I don't see here, that's why I'm asking.
The shortest you can get, with null safety (works naturally for any other objects that implement equals()):
java.util.Objects.equals(a, b);
There is no need for you to reinvent the wheel.
If you are using Java 7 or later, use the java.util.Objects class (as mentioned by Kayaman).
If you are using an earlier version of java, use the Apache BooleanUtils class.
Try a google search for "apache booleanutils" to find out how to get it.
Edit: corrected java version.
It is working for me.
public class MyClass {
public static void main(String args[]) {
Boolean x=true;
Boolean y=true;
System.out.println(compare(x,y)); // true
x=false;
y=true;
System.out.println(compare(x,y)); // false
x=true;
y=false;
System.out.println(compare(x,y)); // false
x=false;
y=false;
System.out.println(compare(x,y)); // true
x=null;
y=null;
System.out.println(compare(x,y)); // true
}
public static boolean compare(final Boolean a, final Boolean b) {
if (a == null || b == null) {
return a == b;
}
return a.equals(b);
}
}
Probe with https://www.jdoodle.com/online-java-compiler
Edit: add exception to null values.

how to break a function in java [duplicate]

This question already has answers here:
How do I break out of nested loops in Java?
(37 answers)
What does it mean to return a value?
(3 answers)
Closed 5 years ago.
guys i am a beginner in java ... i want to make a function to loop through a hashmap for example it contains
0[3],3[4,5],6[2]
and to break when the method isSiteInherited is true else return false... here is what i made
private boolean isInherited() {
boolean isInherited = false;
for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
for (Integer index : entry.getValue()) {
if(isSiteInherited(index)){
break;
}
}
}
return false;
}
if not sites are found inherited return false and if it enters the break it should break from all the method ... so what is wrong with this method
Seems to be like you want to return instead of break. Without the use of labels, break only gets you out of one layer of loops anyway, and in this case, you need to report overall success, which isn't something your current approach does.
private boolean isInherited() {
for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
for (Integer index : entry.getValue()) {
if (isSiteInherited(index)) {
return true;
}
}
}
return false;
}
You can either use a label to break from the outer loop (https://stackoverflow.com/a/886979/4949918).
The better way would probably be to use a boolean to say that you've broken from the inner loop in the outer loop.
private boolean isInherited() {
boolean isInherited = false;
boolean shouldBreak = false;
for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
for (Integer index : entry.getValue()) {
if(isSiteInherited(index)){
shouldBreak = true;
break;
}
}
if (shouldBreak) {
break;
}
}
return false;
}

Check if a String is Integer [duplicate]

This question already has answers here:
What's the best way to check if a String represents an integer in Java?
(40 answers)
Closed 7 years ago.
I need to check whether the String is an Integer. And I found such solution:
private boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Is there a more beautiful and proper way to do this without try/catch clause?
You can try a regex like:
Code
private boolean isInteger(String str) {
return str.matches("\\-?\\d+");
}
Edit
Thanks #Maloubobola for noting that my first attempt would not parse signed integers.
You can try regex. Here is one for positive and negative numbers
private boolean isInt(String string) {
return string.matches("-?\\d+");
}

About substring testing in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm writing some codes that test if there is "xx" in a string. For instance, doubleX("aaxxbb") should return true, and doubleX("axabb") should return false.
Here is my code:
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2) == "xx") return true;
}
return false;
}
Why does doubleX("aaxxbb") return false?
You have to use .equals instead of ==. For more information, follow the duplication message.
return str.contains("xx");
Is a lot clearer though.
You should understand the difference between == and equals: the first one compares references, the second compares actual values.
Your code is wildly inefficient.
I'd try something like this:
private static boolean doubleX(String str) {
return (str.indexOf("xx") != -1);
}
Use equals() for checking the content of a String to another rather than ==. == checks for reference equality.
private static boolean doubleX(String str) {
for(int i=0;i<str.length()-1;i++){
System.out.println(str.substring(i,i+2));
if(str.substring(i,i+2).equals("xx")) return true;
}
return false;
}
Even you can directly code like:
private static boolean doubleX(String str) {
return str.contains("xx");
}

Categories