Do I have this written properly? .equals AND !.equals if statement - java

FIXED. To get the statement to evaluate the way I wanted it to I had to write it this way:
public static Boolean pushCard(String S1, String S2) {
Boolean result = false;
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") && (!S2.equals("water") && (!S2.equals("fire"))))
result = true;
return result;
} //end push card method
I can not tell if this comparison is causing issues. I was using == instead of .equals but then I learned that it was the wrong way to write it. Thanks for the help!
public static Boolean pushCard(String S1, String S2) {
Boolean result = false;
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") || (!S2.equals("water") || (!S2.equals("fire"))))
result = true;
return result;
} //end push card method

Syntactically, your code will compile just fine, and the way you use .equals() method to compare strings is correct. Your use of the ! operator is also correct.
There is no guarantee that your code will not have logical errors though.

The only problem I can see you have "fire" mentioned twice in your second if statement. Otherwise, any problems you might be having could be related to your logic being wrong, since your syntax is pretty much correct and your usage is proper.

It is unclear what you're asking. The second if will always be true. You probably need :
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") && (!S2.equals("water") && (!S2.equals("wind"))))
result = true;

public static Boolean pushCard(String S1, String S2)
{
Boolean result = false;
if (S1.equals("fire") || S1.equals("wind") || S1.equals("water"))
{
(!S2.equals("fire") || !S2.equals("water"))
result = true;
}
return result;
}
/end push card method
you had an extra pair of brackets in the first if statement.
I believe an if statement needs brackets {} when the code inside it is larger than one line.
your second if statement can be altered to just !S2.equals("fire") || !S2.equals("water")

Related

How to use a ternary operator to convert a String that can sometimes be null into an integer in Java?

I am using Talend to filter out some rows from an excel file and they don't allow block statements. Everything has to be simple logic or using the ternary operator. So the problem is that the code/logic I need will be used across every cell in the column, BUT some of the cells are null, some are Strings and the rest are Strings that represent integers.
My logic needs to be this:
Return true if and only if PlanName == null || PlanName == 0 but as you can tell, it will fail when it tries to run this on a cell that contains the null or the cell that contains a String that isn't a number.
Is it possible to have this logic in java without the try-catch or block statements? This is what I have right now:
input_row.PlanName == null || Integer.parseInt(input_row.PlanName) == 0
Thanks!
Edit: Basically, I just need to write logic that does this:
Return true if input_row.PlanName == null OR if input_row.PlanName == 0
This needs to be done without using block-statements or try-catches because I am using Talend. So I can only use logical operators like && and || and I can use ternary operators as well.
In your situation, i'll go for routines : reusable bunch of code, handy for this kind of rules that would be hard to implement without if/else etc.
You can create two Routines in Talend, with static methods that you would be able to use in a tMap or a tJavaRow.
First Routine to know if your plan is a numeric or not :
public static boolean isNumeric(String strNum) {
if (strNum == null) {
return false;
}
try {
double d = Double.parseDouble(strNum);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Then another routine like :
public static boolean correctPlanName(String planName) {
if(Relational.ISNULL(planName)){
return false;
}
else{
if(!isNumeric(planName)){
return false;
}
else {
return true;
}
}
}
Then you call Routines.correctPlanName(input_row.planName) in tMap/tJavaRow.
It should do the trick.
You can use a regular expression to check if the String only contains digits, then check if num == 0.
input_row.PlanName == null || (input_row.PlanName != null && input_row.PlanName.matches("\\d+") && Integer.parseInt(input_row.PlanName) == 0)
Edit: Probably overkill but to cover other cases e.g. floating point types, numbers prefixed with +/-, you could also do:
input_row.PlanName != null && input_row.PlanName.matches("[-+]?\\d*\\.?\\d+") && Double.parseDouble(input_row.PlanName) == 0)

Valid Parentheses Java

I am trying to solve the Valid Parentheses problem in Java (described here among other places: Valid Parentheses)
My code is as follows thus far:
class Solution {
public boolean isValid(String s) {
if(s.charAt(0) ="(") {
if(s.charAt(s.length-1) != ")"){
system.out.println("false");
}
}
if(s.charAt(0) ="[") {
if(s.charAt(s.length-1) != "]"){
system.out.println("false");
}
}
if(s.charAt(0) ="{") {
if(s.charAt(s.length-1) != "}"){
system.out.println("false");
}
}
}
}
Currently I am getting the following error:
Line 4: error: unexpected type
if(s.charAt(0) ="("){
Can anyone advise on what the issue is? I can't at the moment figure it out but feel like it's something simple I'm overlooking.
Two immediate issues:
Character values are single-quoted in Java, e.g. char c = 'c';
Primitive comparison is done with ==. The single equals sign = is used for assignment.
So that line should be:
if(s.charAt(0) == '(') { /* ... */ }
Note that this only fixes the most immediate error you're experiencing. After fixing that, there are some more, for example system.out.println() should be System.out.println().
And, after fixing that, I think you're still a way off from solving the actual assignment. Just keep at it & good luck!
There are some issues in your answer. Robby Cornelissen points you out some issues in his answer. And I also saw 2 errors in your code.
s.length should be s.length().
You don't have a return statement in the isValid method.
Issue 1
In the following statement, you are missing the brackets () after the length. Length is a method in Java that is used to get the length of a Java String that you know already.
if(s.charAt(s.length - 1) != ')')
So your above statement should be as follows.
if(s.charAt(s.length() - 1) != ')')
Issue 2
In your isValid method it's returning a boolean value. The return type of that method is boolean. But you are not returning any boolean value inside your method. So you have to add a return statement. It may be,
return true; or return false; or any boolean variable declared inside isValid method.
it is best to use stack for valid parentheses in Java
class Solution {
public boolean isValid(String s) {
Stack stack = new Stack();
for(int i=0; i<s.length; i++){
if(s[i] =='('){
stack.push(')')
}
else if(s[i] == '['){
stack.push(']')
}
else if(s[i] =='{'){
stack.push('}')
}
else if(s[i] !== stack.pop()){
return false;
}
}
return true;
}
}

Reducing conditional operators efficiently

What I am trying to perform: I am trying to reduce the conditional operators, Since Sonar is giving a error for it
if (!parseBooleanFromString(response.getBuy().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getSell().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getExchange().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()) &&
(!parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeInvestments())))))) {
//Success
} else {
//Failure
}
private boolean parseBooleanFromString(String mStr) {
return Boolean.parseBoolean(mStr);
}
What i have tried:
I am trying to put all the boolean values in a list and check
Is that the best way to do or is there a more efficient way
You can also move these conditions into different functions which internally calls other functions and returns single boolean result. This way there will only one function in above if condition which will internally evaluate and returns result.
Since you're checking if each statement is false, how about you keep a global integer in memory: private int product = 1;. Make a separate method where you calculate the product (replaces the string to boolean parser):
private void updateProduct(String mStr){
if (Boolean.parseBoolean(mStr)) //If true, condition should fail
product *= 0;
else
product *= 1;
}
In essence, you are not running 'if statement' but multiplying the boolean:
product = 1;
updateProduct(response.getBuy().getHasEligibleAccounts());
updateProduct(response.getSell().getHasEligibleAccounts());
//etc
if (product > 0){
//success
} else {
//failure
}
Explanation: If at any point a condition was true, the product will always be 0. The only instance where the product is > 0 is when all statements were false
Not sure what sonar complains about, but you have alot of redundant parenthesis and confusing negations. Using DeMorgans law, you can at least simplify to:
boolean b = parseBooleanFromString(response.getBuy().getHasEligibleAccounts())
|| parseBooleanFromString(response.getSell().getHasEligibleAccounts())
|| parseBooleanFromString(response.getExchange().getHasEligibleAccounts())
|| parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions())
|| parseBooleanFromString(
response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions());
if (!b) {
or if you perfer more java 8 syntax
Stream<Boolean> bools = Stream.of(parseBooleanFromString(response.getBuy().getHasEligibleAccounts()),
parseBooleanFromString(response.getSell().getHasEligibleAccounts()),
parseBooleanFromString(response.getExchange().getHasEligibleAccounts()),
parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()),
parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()));
boolean c = ! bools.anyMatch(e -> e);
if (!c) {
I would do something like this:
private boolean checkEligibility(LaunchPoints response) {
final String trueStr = "true";
if (trueStr.equals(response.getBuy().getHasEligibleAccounts())) return true;
if (trueStr.equals(response.getSell().getHasEligibleAccounts())) return true;
[...]
return false;
}
The idea is, skip the parsing boolean, just check for "true" and make your conditions more readable.

How do I check for nulls and empty string for a needle in a haystack?

Situation: I am coming across a lot of checks in my code. And I would like to know of a way in which I can reduce them.
if(needle!=null && haystack!=null)
{
if(needle.length()==0)
return true;
else
{
if(haystack.length()==0)
return false;
else
{
// Do 2 for loops to check character by character comparison in a substring
}
}
}
else
return false;
Perhaps a different code style would increase the readability of your code and reduce the amount of nested if statements for all of your checks.:
if (needle == null || haystack == null || haystack.isEmpty())
return false;
if (needle.isEmpty())
return true;
// compare strings here and return result.
You could consolidate that logic into a single method on a singleton 'StringFunctions' class and update the usages to use the common method as you encounter them.
You can create a wrapper class for the strings, then add a function like isValid() to them that checks if the length == 0. Use a Null Object that always returns false on isValid() to eliminate the null checks.
If you can create classes that you tell what to do, rather than passing strings that have to be null checked throughout your code, you will get more resuseable results:
class Haystack {
private static final Haystack NULL_HAYSTACK = new Haystack("");
private final String value;
public Haystack(String value) {
this.value = value;
}
public boolean containsNeedle(String needle) {
return needle != null && value.contains(needle);
}
}

evaluate boolean values in Java

I am trying to evaluate the following from a string
boolean value = evaluate("false || true && true && false || true");
I need to get a boolean value of true for this one.
Any ideas on how to solve this problem in the most efficient way?
String value = ("false || true && true && false || true");
boolean result = false;
for (String conj : value.split("\\|\\|")) {
boolean b = true;
for (String litteral : conj.split("&&"))
b &= Boolean.parseBoolean(litteral.trim());
result |= b;
}
System.out.println(result); // prints true
If the only operators are && and ||, then I think this will work:
static boolean eval(String str) {
String s = str.replaceAll("\\s|\\|\\|false|false\\|\\|", "");
return !s.contains("false") || s.contains("||true");
}
For more complicated expressions, I found this library just for that.
Don't know how efficient it is though.
You'll need a small boolean expressions grammar. A bit of recursive parsing should do the trick.
If you don't know how to write such a parser, you may use JavaCC or something similar.
there are parsergenerators available for which you can define a grammar.
But if you only got || and && as operators and true and false as values you can easily do this by yourself, by implmenting a very simple finite state machine:
1.) Split the string into the tokens
2.) parse the left most value by using Boolean.parseBoolean(token) and safe it's value in some instance variable (your state)
3.) combine your instance variable with the next boolean token using the given operator
4.) Repeat step3 until you finished through the whole string
This seems to work although i havent thorougly tested it :)
public class BooleanFSParser {
private boolean parse(String data) {
String[] tokens=data.split("\\s");
boolean state=Boolean.parseBoolean(tokens[0]);
for (int i=1;i<(tokens.length / 2) + 1;i=i+2){
if (tokens[i].equals("&&")){
state=state && Boolean.parseBoolean(tokens[i+1]);
}else{
state=state || Boolean.parseBoolean(tokens[i+1]);
}
}
return state;
}
public static void main(String[] args) {
BooleanFSParser parser = new BooleanFSParser();
boolean val = parser.parse("true && true || false");
System.out.println(String.valueOf(val));
}
}
thats should give you a cirrectly parsed value, but it will get a bit more complex if you allow brackets for example ;)
have fun and check here for the theory
Finite-state_machine

Categories