I try to get an integer (right after "PLAYING:STATION\nID:"out of the String shown in my screenshot by using the following code:
int zahl = Integer.parseInt(sentence.substring(sentence.indexOf("PLAYING:STATION\n
ID:")+1).trim());
But all I get is a NumberFormatException. How can I tell the trim()-method that it has to stop right after the number?
Screenshot of the complete String
Since you must select a specific ID: entry among several ones, I think the best way to proceed is using a regular expression. Using your output sample, I wrote the following code:
String text = "PLAYING_MODE\nID:\nPLAYING:STATION\nID:2\nNAME:wazee.org";
Pattern p = Pattern.compile("PLAYING:STATION\nID:(\\d+)");
Matcher m = p.matcher(text);
if (m.find()) {
int number = Integer.parseInt(m.group(1));
System.out.println(number);
}
which correctly parses the ID number that immediately follows PLAYING_STATION.
You could as well repeatedly work with the overloaded String.indexOf() method (find PLAYING:STATION, then the following ID:, then the following \n). I think the code might be harder to read, but it would still do the job.
I hope this will be helpful...
Cheers,
Jeff
Related
The function StringToDouble always returns zero on passing a variable string.
Let me demonstrate ...
This is what I have so far.
string balance = "12.50USD";
// lets extract the double only from the string
int x = StringReplace(balance,"USD",""); // now we have a plain number
Print(balance); // "12.50"
double balance_only = StringToDouble(balance);
Print(balance_only) ; // Zero? Why?
Well according to the documentation here and here
This is supposed to work? Right? What am I missing?
I even tried to add empty strings on the sides to trick the function but still
double b = StringToDouble(StringConcatenate("",balance,""));
Print(b); // Zero , Why :(
What seems to be the problem here?
After installing and unistalling a couple of MT4 instances,
It was there all along,
For some reason I was also using StringSplit function i.e
StringSplit(extracted_balance_string," ", &results[]);
Instead of
StringSplit(extracted_balance_string,StringGetCharacter(" ",0), &results[]); // the space was a special character
I missed that, my bad :D
Let say I have below dummy code
import a_package as ap
calc = ap.func.func1()
So in my case calc is a function or method. However I want python to consider this as a string and split that based . and then return the last element i.e. return func1.
Is there any direct way to achieve the same?
As the other reviewers noted, you will need to start with a string if you want to perform a string operation. Assuming you have a way of getting a string in the form you showed, here are two examples of how to get the part of that string you are interested in:
import re
my_string = "ap.func.func1()"
# Should be sufficient for the use case you describe
my_split_string = s.split(".")
print(my_split_string[-1])
# More powerful (but more complex) if you have extended use cases
match = re.search(r"\.([^.]+)$", my_string)
print(match.group(1))
func1()
func1()
Thank you in advance for your time and help.
Exercise:
Write the code for sumDigitsInNumber(int number). The method takes a three-digit whole number. You need to calculate the sum of the digits of this number, and then return the result.
Consider this example:
The sumDigitsInNumber method is called with argument 546.
Example output:
15
CODE:
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
}
}
This is a solution and the task has been passed. The problem is the solution had been implemented by someone (not by me) therefore I can't understand How this function does its job.
I tried to test the function parts separately, just to see what would happen, and here is the result:
number%10 = 546%10;
546/10 = 54;
output:
6+sumDigitsInNumber(546/10) - which is totally wrong.
I don't understand HOW sumDigitsInNumber is treated by the ternary operator in there and how this short line of code:
return number ==0? 0:number%10+sumDigitsInNumber(number/10);
makes such a complicated calculation?
Can anyone explain it to me in a way it would have explained to a Java-child?
TYVM in advance.
So, using the example number of 546, let's step through the code.
In the first run, it does indeed return 6+sumDigitsInNumber(546/10), that is all correct.
Because sumDigitsInNumber's parameter (number) is int, the decimal portion of the division is truncated, resulting in essentially a floor operation (forced round down). And we recursively call sumDigitsInNumber's, so we just keep "looping" that section of code. So for the second run, it is equivalent to sumDigitsInNumber(54), plus the additional 6 from the first run (6+sumDigitsInNumber(54)).
The second call returns 4+sumDigitsInNumber(54/10) by following the same logic as the first call. This is equivalent to 4+sumDigitsInNumber(5).
Then we run the whole process again, which returns 5+sumDigitsInNumber(5/10), equivalent to 5+sumDigitsInNumber(0).
The final call, sumDigitsInNumber(0), will return 0 because of the ternary operator in the return statement.
To expand this all out:
sumDigitsInNumber(546)
= 6+sumDigitsInNumber(546/10) = 6+sumDigitsInNumber(54)
= 6+(4+sumDigitsInNumber(54/10)) = 6+(4+sumDigitsInNumber(5))
= 6+(4+(5+sumDigitsInNumber(5/10))) = 6+(4+(5+sumDigitsInNumber(0)))
= 6+(4+(5+0))
= 6+(4+(5))
= 6+(9)
= 15
Ok, so I am a little lost with Processing Programming Language again, so wondering if anyone can help my brain become unblocked?
This is the question - "Write a program which compares two numbers, if one of the numbers is larger than the other then the two numbers are added together and the result is printed in the console window."
So I have got this, but im getting errors on just the 'int' value code which is making me think ive completely misunderstood this?.. possibly misunderstood how the language works :/
Here is my code;
void setup() {
int a = 30
int b = 20
if (a > b) {printIn("a+b");}
}
Generally it helps if you post what errors you're getting. However, in this case you have a very basic syntax problem: you need to terminate your statements with semicolons - including the assignments. Eg: int a = 30;
Oh, and it's println (with a lowercase L) not printIn. And, as noted by logoff, you're doing the sum inside a quoted string, which will just print as a literal.
If I understad it correctly you have to declare the variables outside the setup() method. Intialization can be done inside the method.
The l in println(); should be lowercase.
There is no need for the quotes around the variables.
This works:
void setup() { int a = 30; int b = 20; if(a > b) {println(a + b); }}
this question feels like it would have been asked already, but I've not found anything so here goes...
I have constructor which is handed a string which is delimited. From that string I need to populate an object's instance variables. I can easily split the string by the delimited to give me an array of strings. I know I can simply iterate through the array and set my instance variables using ifs or a switch/case statement based on the current array index - however that just feels a bit nasty. Pseudo code:
String[] tokens = <from generic string tokenizer>;
for (int i = 0;i < tokens.length;i++) {
switch(i) {
case(0): instanceVariableA = tokens[i];
case(1): instanceVarliableB = tokens[i];
...
}
}
Does anyone have any ideas of how I do this better/nicer?
For what it's worth, I'm working in Java, but I guess this is language independant.
Uhm... "nasty" is in the way the constructor handles the parameters. If you can't change that then your code snippet is as good as it may be.
You could get rid of the for loop, though...
instanceVariableA = tokens[0];
instanceVariableB = tokens[1];
and then introduce constants (for readibilty):
instanceVariableA = tokens[VARIABLE_A_INDEX];
instanceVariableB = tokens[VARIABLE_B_INDEX];
NOTE: if you could change the string parameter syntax you could introduce a simple parser and, with a little bit of reflection, handle this thing in a slightly more elegant way:
String inputString = "instanceVariableA=some_stuff|instanceVariableB=some other stuff";
String[] tokens = inputString.split("|");
for (String token : tokens)
{
String[] elements = token.split("=");
String propertyName = tokens[0];
String propertyValue = tokens[1];
invokeSetter(this, propertyName, propertyValue); // TODO write method
}
Could you not use a "for-each" loop to eliminate much of the clutter?
I really think the way you are doing it is fine, and Manrico makes a good suggestion about using constants as well.
Another method would be to create a HashMap with integer keys and string values where the key is the index and the value is the name of the property. You could then use a simple loop and some reflection to set the properties. The reflection part might make this a bit slow, but in another language (say, PHP for example) this would be much cleaner.
just an untested idea,
keep the original token...
String[] tokens = <from generic string tokenizer>;
then create
int instanceVariableA = 0;
int instanceVariableB = 1;
if you need to use it, then just
tokens[instanceVariableA];
hence no more loops, no more VARIABLE_A_INDEX...
maybe JSON might help?
Python-specific solution:
Let's say params = ["instanceVariableA", "instanceVariableB"]. Then:
self.__dict__.update(dict(zip(params, tokens)))
should work; that's roughly equivalent to
for k,v in zip(params, tokens):
setAttr(self, k, v)
depending on the presence/absence of accessors.
In a non-dynamic language, you could accomplish the same effect building a mapping from strings to references/accessors of some kind.
(Also beware that zip stops when either list runs out.)