I am attempting to eliminate a large amount of IF/ELSE statements from my code with the use of the ternary operator.
//Checks to see if person exists //if not then add //else print
println doesPersonExist(personName) ? addPerson(personName) : 'No such person'
The problem is that if the addPerson(personName) method is executed then NULL is printed due to the println. Is there anyway of NULL from printng to the console? I understand i could remove the println but then 'No such person' would not print.
UPDATE: I finally managed to get this working as required - i simply removed the println and also 'No such person' and replaced them with this:
doesCarrierExist(carrierName) ? exists() : addCarrier(carrierName)
Where the exists method simply called a println statement within the base class. I hope this helps anyone that has a similar problem in the future.
In your code you mix 2 different actions.
The print method.
The addPerson(personName).
And you wish to print that into the screen.
The best way is handling it as 2 separate handles one for each action (for the addition and for the printing).
If the addPerson(personName) returns a String result you can print to the console the result by using the following Groovy code section:
def textResult = doesPersonExist(personName) ? addPerson(personName) : ""
println(textResult)
Note: If you are using Java language replace the 'def' with 'String'.
Related
I have the following statement...
personName[0] = n[y].getName().equals ("Penny") ? personName[0]++ : personName[0];
personName[] is an integer array. getName returns a string. Every time getName is equal to "Penny," I want personName[0] to add one. How should I do this? When I run it, personName[0] does not add one and I don't know why.
Don't try to abuse the conditional operator like this. A plain old if is vastly more readable and concise:
if (n[y].getName().equals ("Penny")) {
personName[0]++;
}
If you must use a conditional operator, it would be clearer to use +=:
personName[0] += n[y].getName().equals ("Penny") ? 1 : 0;
If you want just to increment personName[0], wouldn't be better to use just an if? Sometimes, conditional operator is to much for simple problems.
I am using the Xtend templates to write a small program. I try using the IF statement, but every time I execute it it prints the variable in the console, which I dont want it to.
«IF x==y»
The jump value is «database.get(2)»
«jump_var_letter = String.charAt(1)»
«old_jump_ahd=database.get(2) »
«ENDIF»
Here the database is an array of integers and String is an array of letters. Here I just want it to print the value found at database.get(2) i.e 5. The last two expressions befor the ENDIF is meant for assignning a few values( which need not be printed)
The jump value is 5
Instead I get
The jump value is 5
D
5
Could somebody please tell me how I could stop printing the other two values.
Thank you in advance for your help..
After looking for sometime on the net I found that you could prevent the printing of the expreesions in between by using block expressions and then returning a null expression. (Although this method is not encouraged, I found that it provides me the result I wanted). So the expression I posted could be written as:
«IF x==y»
The jump value is «database.get(2)»
«{jump_var_letter = String.charAt(1); "" }»
«{old_jump_ahd=database.get(2); ""} »
«ENDIF»
This prints
The jump value is 5.
Inside Fitnesse DoFixture, you can use check keyword to compare one of the objects with an expected value. I was wondering if there is a check not equal that exists to make sure the expected and actual do not match up.
I have tried using that set of keywords but it is not supported. There is a reject keyword for DoFixtures, but it does not accomplish the goal. Anyone know of a method? For a testing framework, it seems like it should be obvious, but I've had a rough time digging through the UserGuide.
Example:
|check not equal| guid | c1acff01-e45b-4b7d-b6f5-84f8830ef6b4 |
Scenario Pass: guid != c1acff01-e45b-4b7d-b6f5-84f8830ef6b4
I was unable to find this type of test condition, so instead, I put the logic inside the Fixture code with the expectation to return true when a != b. In the Fit code, I had the following:
|check|guidsNotEqual|true|
With fitSharp you can have
|check|mymethod|fail[myvalue]|
This will pass if mymethod is not equal to myvalue. I don't think this works with the Java FitLibrary.
There is an option (might be added after the question was asked). It is possible to check for something not equal by using 'check not'.
So
|check not|this is true|false|
will return true
I have written these three lines below inside my Java code:
ArrayList<String> QuestionID = new ArrayList<String>();
;
ArrayList<String> QuestionType = new ArrayList<String>();
It compiles and runs perfect without any problems.
Why does it do so?
I cannot understand why I am not getting any warning or error in second line.
Somebody decided that an empty statement is valid. That's all there is to it. Allowing empty statements is sometimes useful, for instance for for loops with empty bodies.
As an example, here's how to find the root node of a tree (assuming there's a parent linkage, and that the root node has no parent):
for (Node parent = anyChildNode; parent.getParent() != null; parent = parent.getParent())
; // this for loop has no body, so an empty statement takes its place
Because you are writing an empty statement, which is perfectly valid.
Here you will find some more explanation.
From the above link -
The usefulness of this type of statement is limited. The main use that
I can think of is to fulfill the statement required for a loop
structure.
Here is an example that I recently used:
while ( sf(++n) != i) ;
This loop will constantly call the method sf with increasing values of
n until the return value of sf(n) is equal to i. Each loop in Java
must have some code to execute in the loop body. In this case, all
necessary work is done in the condition, and so the mandatory loop
body is an empty statement.
While there may be other (more clear) ways of writing this bit of
code, this is an example of where that empty statement can be used.
Not only is it allowed, but it has its own section in the JLS. As expected:
An empty statement does nothing.
Even more:
Execution of an empty statement always completes normally.
Which means that the following code:
;
will never throw an exception. Good to know ;-)
";" is considered as a line code without any instructions.
There's no syntax error.
#if DEBUG
#define ASSERT(_x) Assert(x)
#else
#define ASSERT(_x)
#endif
ASSERT(test); // Results in null statement in non-debug builds
Empty semicolon means there is "empty statement" before that. Thats perfectly valid case.
; means "execute nothing";
Good article about usage of empty statement
Its a valid statment and similar to instructing compiler to do nothing.
Empty statement came to Java from C where you could find it very useful for things like
strcpy(char *s, char *t) {
while(*s++ = *t++);
}
Empty Semi Colon is a valid token in JAVA and it denotes an empty statement.
I had an if statement checking some value, And encountered a weird bug(Not sure!). My code was incorrect syntactically and in result it produced a wrong result, however eclipse didn't raised any error while compiling. Why My below code worked?
if((this.trackPointList.get(point).getTurnOutId().equals(seg.getSegRef().getTurnOut())) && seg.getSegRef().getKind().equals("arc")); // <---- See here I have semicolon
{
... code to run ...
}
Above code check only first condition and ignores seg.getSegRef().getKind().equals("arc") but I guess this should raised an issue at compile time, Am I right? My logic worked once I debugged it by skimming line by line and found this semicolon. I will appreciate if someone could explain, if it is a valid syntax.
Enlighten Me, Please!
The ; makes Java think that the body of the if conditional is complete, even if there is no other code preceding it. In effect, the code in the if statement is executed, but no body exists because the ; is there.
The { ...code to run...} is just a code block that executes, and anything declared inside that block is not visible outside the block. It will always run here because it's not part of the if block.
edit: here's another stack overflow question about the { } blocks: What do curly braces in Java mean by themselves?
The code is syntactically correct. You can write ifs without braces, like:
if(condition) statement;
Having empty statements is also valid. For instance this code is valid:
int a = 0;;
;;;
So an empty if is valid as well, although it doesn't make much sense :)
if(condition);
An if statement followed by a semicolon is called an "empty if statement".
It rarely is of any use, but it's syntactically legal.
You can write something like this
if ( doSomethingThatReturnsABoolean() )
; // Empty statement
else
doSomeOtherThing()
but it would be better to write
if ( !doSomethingThatReturnsABoolean() )
doSomeOtherThing()
Regarding your observation that only the first condition gets checked:
If the first condition returns false the second condition will not get checked, because
(false && secondCondition)
always equals to false, so the value of secondCondition is irrelevant.
The ; after the if(..) statement represents an empty statement that is executed conditionally when the if(..) evaluates to true. The { .. } represents a code block that always executes with it's own scope.
The second condition may be ignored if the first condition is false due to short-circuit evaluation.
if(condition); is equivalent to if(condition){}
same thing with for loop & while loop:
for(;condition;); is equivalent to for(;condition;){}
while(condition); is equivalent to while(condition){}