How to shorten code when I do a variable assignment in a condition in Dart? - conditional-statements

Here's the ugly long code:
var i;
if(true)
i = 1;
else
i = 0;
When I try this:
var i = (true ? 0 : 1);
it doesn't work resulting in an error on the following line. I guess I was a bit inattentive reading Dart's syntax specs, so can anybody show me the right way?

This looks perfectly fine from a syntax point of view. You can omit the parentheses.
I get a warning 'Dead code' at '1' with your example because of 'true'.
The Darteditor shows you a hint that you wrote code that may contain a bug because he knows your expression can never evaluate to 1 because of the hardcoded 'true'.
void main(List<String> args) {
var b = true;
var i = b ? 0 : 1;
}
doesn't produce a warning.

Related

understanding a piece of code with ``boolean`` and ``switch``

i was looking some examples of interactions with the keyboard and stumbled upon this code that i found interesting. But i'm having trouble understanding a certain part of it(it's marked down below).I don't get how all this whole ''boolean'' declaration, ''switch'' and ''CASE'' works, i tried to look in the reference but still. Could someone explain in a simple maner how these work?
float x = 300;
float y = 300;
float speed = 5;
boolean isLeft, isRight, isUp, isDown;
int i = 0;
void keyPressed() {
setMove(keyCode, true);
if (isLeft ){
x -= speed;
}
if(isRight){
x += speed;
}
}
void keyReleased() {
setMove(keyCode, false);
}
boolean setMove(int k, boolean b) {// <<<--- From this part down
switch (k) {
case UP:
return isUp = b;
case DOWN:
return isDown = b;
case LEFT:
return isLeft = b;
case RIGHT:
return isRight = b;
default:
return b; }
}
Questions like these are best answered by the reference:
Works like an if else structure, but switch() is more convenient when you need to select between three or more alternatives. Program controls jumps to the case with the same value as the expression. All remaining statements in the switch are executed unless redirected by a break. Only primitive datatypes which can convert to an integer (byte, char, and int) may be used as the expression parameter. The default is optional.
The rest of the code is setting the corresponding variable to whatever value you passed in as the b parameter, and then returning it.
You should get into the habit of debugging your code. Add print statements to figure out exactly what the code is doing.

How to move to another part of the code using an if statement

in my code I have the following if statement:
if (a.count >= 2) {
t2 = array[b % a.count];
array[0] = t2;
}
I have another if statement that goes like the first. What I want it to do is if a <= 0 then goto a certain line, or skip over certain parts of code. How would I do this? I was thinking something along the lines of
if (a.count <= 0) {
goto line 96
}
This wouldn't work, the syntax is wrong, but how would I do this?
Goto statements are generally considered bad programming and excessive utilization of them can lead to code that is hard to maintain and debug.
That said, if/else/else if provide all the functionality you need.
I recommend putting the code you need to run inside that if statement in a separate method and then calling it from the if statement.
if (a.count <= 0) {
nameOfNewMethod();
}
//somewhere else
- (void) nameOfNewMethod {
//code here
}
Put the lines of code you want to "goto" in a function (or if appropriate, a block) and call the function (or block). If there are lines of code you want to skip, you can always return early out of a function, or use an else block?
There is in fact a goto command in Objective-C. To utilize it, you have to create a label, ex:
marker:
and jump to it like so within the same method:
goto marker;
But you can't declare any variables between those two commands. All the variables have to be created before the jump so that they still exist after.
Here's an example of how to use goto:
int x = 0;
if (a.count <= 0) {
goto marker;
}
x = 5;
marker:; // <-- semi-colon indicates the label is followed by an empty statement, thus allowing for immediate variable declaration
int y = x + 7;
In that case, if a.count <= 0, y == 7, else y == 12.

How to preserve whitespace when we use text attribute in Antlr4

I want to keep white space when I call text attribute of token, is there any way to do it?
Here is the situation:
We have the following code
IF L > 40 THEN;
ELSE
IF A = 20 THEN
PUT "HELLO";
In this case, I want to transform it into:
if (!(L>40){
if (A=20)
put "hello";
}
The rule in Antlr is that:
stmt_if_block: IF expr
THEN x=stmt
(ELSE y=stmt)?
{
if ($x.text.equalsIgnoreCase(";"))
{
WriteLn("if(!(" + $expr.text +")){");
WriteLn($stmt.text);
Writeln("}");
}
}
But the result looks like:
if(!(L>40))
{
ifA=20put"hello";
}
The reason is that the white space in $stmt was removed. I was wondering if there is anyway to keep these white space
Thank you so much
Update: If I add
SPACE: [ ] -> channel(HIDDEN);
The space will be preserved, and the result would look like below, many spaces between tokens:
IF SUBSTR(WNAME3,M-1,1) = ')' THEN M = L; ELSE M = L - 1;
This is the C# extension method I use for exactly this purpose:
public static string GetFullText(this ParserRuleContext context)
{
if (context.Start == null || context.Stop == null || context.Start.StartIndex < 0 || context.Stop.StopIndex < 0)
return context.GetText(); // Fallback
return context.Start.InputStream.GetText(Interval.Of(context.Start.StartIndex, context.Stop.StopIndex));
}
Since you're using java, you'll have to translate it, but it should be straightforward - the API is the same.
Explanation: Get the first token, get the last token, and get the text from the input stream between the first char of the first token and the last char of the last token.
#Lucas solution, but in java in case you have troubles in translating:
private String getFullText(ParserRuleContext context) {
if (context.start == null || context.stop == null || context.start.getStartIndex() < 0 || context.stop.getStopIndex() < 0)
return context.getText();
return context.start.getInputStream().getText(Interval.of(context.start.getStartIndex(), context.stop.getStopIndex()));
}
Looks like InputStream is not always updated after removeLastChild/addChild operations. This solution helped me for one grammar, but it doesn't work for another.
Works for this grammar.
Doesn't work for modern groovy grammar (for some reason inputStream.getText contains old text).
I am trying to implement function name replacement like this:
enterPostfixExpression(ctx: PostfixExpressionContext) {
// Get identifierContext from ctx
...
const token = CommonTokenFactory.DEFAULT.createSimple(GroovyParser.Identifier, 'someNewFnName');
const node = new TerminalNode(token);
identifierContext.removeLastChild();
identifierContext.addChild(node);
UPD: I used visitor pattern for the first implementation

Unable to check the value of a variable in Objective-C

I need to check a variable vi_theIndex for its value. At the given moment it has a value of 65.
I want to check if vi_theIndex is bigger or equal to zero AND smaller than 32.
Right now I do it like this:
long long vi_theIndex = 65;
if ((vi_theIndex >= 0) && (vi_theIndex < 32) )
{
//Case true
}
else
{
//Case false
}
I realized that the results are wrong for 65. The second case should come up but the first case becomes true. Why is this?
I tried this:
long long vi_theIndex = 65;
bool limitFlag1, limitFlag2;
limitFlag1 = (vi_theIndex <= 0);
limitFlag2 = (vi_theIndex = 65);
limitFlag2 becomes true and limitFlag1 becomes undefined, the debugger doesn´t even stop there on my breakpoint. It looks like C doesn´t understand the '<', '<=' or '>' signs. This also happens when I use the '<' or '>' sign alone like here:
limitFlag1 = (vi_theIndex < 0);
limitFlag1 is not defined.
Can somebody please shed some light on this?
You must not be showing your real code for your first example - as you say, "case false" should be executed.
Your second example has a problem - you have vi_theIndex = 65, rather than vi_theIndex == 65, which you probably meant. The statement as you have it is always true. limitFlag1 will be 0 - I'm not sure what you mean by it "becomes undefined" - are you not showing your real code here, too?

libxml : xpath not found?

I'm completly new to XML, libxml and xpath. Therefore I wanted to parse a very simple XML expression
<count>
<active type="integer">1</active>
</count>
I want to retrieve the value 1. I wrote the following code that uses libxml (this code contains objective c code):
const unsigned char* xPathExp = (const unsigned char*) "count/active/text()";
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression( xPathExp, xpathCtx);
xmlNodeSetPtr nodeSetPtr = xpathObj->nodesetval;
if( nodeSetPtr != 0 ) {
xmlNode* node = nodeSetPtr->nodeMax > 0 ? nodeSetPtr->nodeTab[0] : 0;
if( node != 0 ) {
NSLog(#"Active Projects = %#", [self stringFromCString:node->name] );
} else {
NSLog(#"Node for xpath Exp: count/active/text() does not exist.");
}
} else
NSLog(#"nodeSetPtr is null");
xmlFreeDoc(doc);
xmlCleanupParser();
It turns out that the output of this code is
nodeSetPtr is null
So that confuses me. I ran an online xpath evaluator on the xml above and the xpath expression "count/active/text()" return 1.
What am I doing wrong here?
It may be as simple as your document setup and what the root element is. first, try //count/active/text(). If that works, then try /count/active/text(). In general, try not to use // unless you really want to match anywhere (great for debugging this particular problem, though). /count should find the count element against the root.