If condition statement erroring "There are coding standard violations (Java) - java

I am working on a customization where conditions are based on participant disability value "Y" and relation code child value "C".
Build Error points to: "There are coding standard violations" ;
Avoid using if statements without curly braces.
If client wants to display disability footnote on the page and dpnd is disable ; baseFtnt2 is the footnote that needs show.
I believe the error is in the syntax:
if (dpndEvntBean.getHasDpndDsbl()
&& item.getDsblCd().trim().equals("Y")
&& ddb.getRltnCd().trim().equals("C"));
{
ddb.addFtntIdListEntry("baseFtnt2");
}
Any help would be appreciated!
Thanks in advance

You should remove the ; at the end of the 3th line
if (dpndEvntBean.getHasDpndDsbl()
&& item.getDsblCd().trim().equals("Y")
&& ddb.getRltnCd().trim().equals("C")) // Removed ';'
{
ddb.addFtntIdListEntry("baseFtnt2");
}
otherwise it would mean
if (dpndEvntBean.getHasDpndDsbl()
&& item.getDsblCd().trim().equals("Y")
&& ddb.getRltnCd().trim().equals("C"))
{
}
{
ddb.addFtntIdListEntry("baseFtnt2");
}
So an empty block for the if and the ddb call called always.

Related

How to put 2 condition in one statement actiolistener in java? [duplicate]

I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}

Whats wrong with my syntax on if statement using LineReader?

Can anyone see why I'm getting an error on this:
r = new LineNumberReader(new FileReader(txtFile));
for (int i = 1; i < txtFile.length(); i++){
if (r.getLineNumber() = (6*i)+1 || r.equals(1)) {
//code here
}
}
Error is:
Multiple markers at this line
- The left-hand side of an assignment must be a
variable
- The left-hand side of an assignment must be a
variable
- Syntax error on token ")", delete this token
But i can't see whats the issue is. Error is on the 3rd line
EDIT: I love you all, you've saved me once again! Guess I've spent to long with VB.net....
if (r.getLineNumber() = (6*i)+1 || r.equals(1))
should be
if (r.getLineNumber() == (6*i)+1 || r.equals(1))
Not sure what do you want to check with this r.equals(1) but you will most probably get false all the time, since you are compartir equallity between a LineNumberReader and an Integer.
In JAVA you compare two objects with two equals == , but in the if statement you put only one =.
So replace the = in the second line with the ==.
And please, write down this error somwhere you can remember it. Becouse every time you'll see it, then you'll know that it is caused by this same problem (mostly).
My wild guess would be:
if (r.getLineNumber() == (6*i)+1 || r.getLineNumber == 1)
should be == in stead of =
r.getLineNumber() == (6*i)

Function that returns true if string contains "xyz" not directly preceeded by a period?

I am really confused by a CodingBat Java exercise. It's suppose to return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.
xyzThere("abcxyz") → true
xyzThere("abc.xyz") → false
xyzThere("xyz.abc") → true
I couldn't figure this out for the life of me so I just looked up a solution online and I'm so confused why this works. Any wanna help clarify? I added some comments on the code as to what I am having trouble with.
public boolean xyzThere(String str) {
int pos =0;
while ((pos = str.indexOf("xyz")) >= 0) { `
The while ((pos = str.indexOf("xyz")) >= 0) { confuses me here. I tried this without the double brackets and it didn't work. Does the double brackets do some kind of casting to an int or something? Also how does pos even get assigned to something in a while statement, does it run the part on the right first then assigns it?
if (pos == 0)
return true;
if (str.charAt(pos-1) != '.')
return true; // found it
// xyz was preceded by a period so skip over this match
str = str.substring(pos+1);
I am so confused how it can even reach str = str.substring(pos+1); I thought I could just take this out entirely but it broke the entire program. Since it's an if statement and it has no brackets to make it a block statement, how or when is this reached, and what is the logic behind it? What the purpose of this statement, as it seems so pointless to me. Even if it does get reached in the code, what does it do?
}
return false; // no luck
}
For any readers, here's the xyzThere problem: http://codingbat.com/prob/p136594
Since you were initially looking for any solution, here's a non-looping solution:
public boolean xyzThere(String str) {
return str.replaceAll("\\.xyz", "").contains("xyz");
}
Regarding double parens: if you remove the double parens, then it won't compile, because the compiler interprets that as trying to assign str.indexOf("xyz") >= 0 to the pos variable, and the types, boolean and int respectively, don't match.
You will notice that assignment is at the bottom of java operator precedence - without the extra parens, it will occur last: http://www.cis.upenn.edu/~palsetia/java/precedenceTable.html
unle
Regarding assignment in a loop - yes this is valid. The value assigned to pos is then compared with 0.
Regarding str = str.substring(pos+1);. This is how the posted solution is removing ".xyz" from the string which finally determines whether the string still contains "xyz".
Regarding the if statement
if (str.charAt(pos-1) != '.')
return true; // found it
Without brackets, the implied scope of the if statement if the next statement. The style here is generally considered back practice for just the reason you've found and should be rewritten as either:
if (str.charAt(pos-1) != '.') {
return true;
}
or
if (str.charAt(pos-1) != '.') return true;
while ((pos = str.indexOf("xyz")) >= 0) {
indexOf returns -1 if the string is not found so this is going to continue looking so long as an "xyz" is found in the string. See later for how it makes sure this is another occurrence rather than the same one again.
The extra bracket is to stress that there is also an assignment going on here. pos is being updated to the start of the "xyz" that was found (or -1 if no more).
if (pos == 0)
return true;
It is allowed at the start - I guess.
if (str.charAt(pos-1) != '.')
return true;
If there is not a "." just before it then we're done.
str = str.substring(pos+1);
Throw away everything up to and including the "x" of the discovered "xyz". Makes sure that next time around we don't find the same one again.
return false;
We got to the end without finding one - it must not be there.
The following code snippet needs "double brackets" (really double parentheses -- it pays to be precise because brackets are a different character) because the parens group different parts of what amounts to a mathematical expression. What you think are double brackets are actually single parens grouping different parts of the expression from what you probably think they're grouping.
while ((pos = str.indexOf("xyz")) >= 0)
^-----^
^------------------------^
^-------------------------------^
If you switch to an IDE instead of the simple text editor that you're probably using, the IDE will highlight matching parentheses so you can see which opening paren is related to which closing paren. There's no casting or other magic going on. Parentheses, brackets, angle brackets, and curly braces. are just there to show the beginning and end of particular groups of things, whether it's an expression, an expression within an expression, a data set, etc.

Check whether string contains sub string, without using the java predefined methods

I need to find whether a given sub string contains within a given string.But the constraint is I cannot use any predefined Java methods.
I have tried as follows.
public void checkAvailability()
{
len=st.length();
for(int i=0;i<len;i++)
{
for(int j=0;j<substr.length();j++)
{
if(st.charAt(i)==substr.charAt(j))
{
if(j!=substr.length()-1 && i!=st.length()-1)
{
if(st.charAt(i+1)==substr.charAt(j+1))
{
available=true;
//j++;
count++;
}
}
}
}
}
if(available)
{
System.out.println("The character is available " + count + " times");
}
else
{
System.out.println("The character is not availabe");
}
}
But it doesn't give the correct answer. Can somebody help please?
Thank you in advance...
There are a few mistakes in your code - I'll describe an algorithm without writing the code to avoid spoiling the learning exercise for you:
The outer loop needs to go from 0 to st.length()-substr.length()
The inner loop needs to check st.charAt(i+j) and substr.charAt(j)
The inner loop needs to stop as soon as you find a mismatch; set a mismatch flag, and break
If the inner loop completes without finding a mismatch, then i is the position of the first match.
Note that this is the most straightforward algorithm. It does not perform well when the st is long, and substr has lots of "false positives" In general, you can do better than that, for example, by using the KMP algorithm.

If else seems to be ignored in my java application

I just started programming in java and i am creating a simple waiting list.
it al seems to work well but i decided to include a if else construction to check the textfield not beeing empty. the problem is that it seems to be ignored because i don't get a error or something.. and i googled alot for the if else example and i can't solve the problem somehow.. what am i doing wrong? below you can find the relevant code. Thanks in advance.
public void actionPerformed(ActionEvent e) {
// check if veld1 is filled in.
if ( veld1 == null || veld1.equals( "" ) ) {
// give error
System.out.println("U heeft niets ingevuld in veld1");
}
else {
veld4.setText( veld3.getText() );
veld3.setText( veld2.getText() );
veld2.setText( veld1.getText() );
textveld1.append( veld4.getText() + "\n" );
veld1.setText("");
}
}
It seems veld1 is not a string, but some Swing control.
You probably want to do
if(veld1.getText() == null || veld1.getText().equals( "" )
It is difficult to grant without seeing the rest of it, but veld1.equals("") looks suspicious. You are comparing veld1 to the empty String, but veld1 looks like a component. Maybe you meant veld1.getText().equals("") (and, similarly, veld1.getText() == null)
If the veld1 holds a JTextField, you probably want to change the statement to veld1 == null || veld1.getText() == null || veld1.getText().equals( "" ), as in your current code you check if the field itself exists, not its content.
veld1.equals("") is not the same as veld1.getText().equals(""), the first one is comparing the veld1 object to an empty string, and will always be false.

Categories