string variable returning as double - string

Create a method called parseEqn which will receive 1 String variable and return the double value of the expression passed to it.
parseEqn("123+23") → 146.0
parseEqn("3+5") → 8.0
parseEqn("3-5") → -2.0
so thats the question^^^^ and i think what i need to do is first use a string tokenizer to split the string up and then convert the tokens into doubles and from there add or subtract depending on the operator...but im not sure..
this is what i have so far
public double parseEqn(String str) {
StringTokenizer st = new StringTokenizer(str, "+-", true);
String first= st.nextToken();
String op= st.nextToken();
String second= st.nextToken();
double num1 = Double.parseDouble(first);
double num2 = Double.parseDouble(second);
if (op.equals("+")){
return num1+num2;
}
else (op.equals("-")){
return num1-num2;
}
i have no clue though....

Writing an expression parser is not a trivial task. The standard algorithm for parsing arbitrary infix expressions is the shunting-yard algorithm. The idea is to run through each token and build a Reverse Polish Notation (RPN) expression from the input. An RPN expression is essentially a stack-based list of operations that is very easy for a computer to work with (and easy to write code to evaluate).

Related

string(int), string(int32) and string([]int32) are all valid but string([]int) is invalid - what's the rationale here?

(I'm using Go 1.14.6.)
The following statements would all output the char a
Println(string(int(97) ) )
Println(string(int32(97) ) )
Println(string([]int32{97} ) )
But
Println(string([]int{97} ) )
would cause compile error
cannot convert []int literal (type []int) to type string
The behavior is confusing to me. If it handles string(int) the same as string(int32), why it handles string([]int) different from string([]int32)?
rune which represents a unicode code point is an alias for int32. So effectively string([]int32{}) is the same as string([]rune{}) which converts a slice of runes (something like the charaters of a string) to string. This is useful.
int is not int32 nor rune, so it's not logical what converting []int to string should be, it's ambiguous, so it's not allowed by the language spec.
Converting an integer number to string results in a string value with a single rune. Spec: Conversions:
Conversions to and from a string type
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to "\uFFFD".
This is confusing to many, as many expects the conversion result to be the (decimal) representation as string. The Go authors have recognized this, and have taken steps to depcecate and remove it from the language in the future. In Go 1.15, go vet already warns for such conversion. Go 1.15 release notes: Vet:
New warning for string(x)
The vet tool now warns about conversions of the form string(x) where x has an integer type other than rune or byte. Experience with Go has shown that many conversions of this form erroneously assume that string(x) evaluates to the string representation of the integer x. It actually evaluates to a string containing the UTF-8 encoding of the value of x. For example, string(9786) does not evaluate to the string "9786"; it evaluates to the string "\xe2\x98\xba", or "☺".
Code that is using string(x) correctly can be rewritten to string(rune(x)). Or, in some cases, calling utf8.EncodeRune(buf, x) with a suitable byte slice buf may be the right solution. Other code should most likely use strconv.Itoa or fmt.Sprint.
This new vet check is enabled by default when using go test.
We are considering prohibiting the conversion in a future release of Go. That is, the language would change to only permit string(x) for integer x when the type of x is rune or byte. Such a language change would not be backward compatible. We are using this vet check as a first trial step toward changing the language.

Representing a non-numeric string as in integer in Julia

I'm looking for a simple and invertible way to represent a Julia string by an integer (e.g. for cryptography). To be clear, I'm not considering string representations of integers like "123", but arbitrary strings like "Hello". The representation doesn't need to be human-readable, but it needs to be easily invertible back to a unique string (so not a hash). It doesn't need to be efficient; I'm just looking for something as simple as possible. (Also, it's fine if it only works on a small character set, e.g. lowercase Roman letters.)
One naive way would be to collect the string into a vector of chars, parse(Int, _) each char to an integer, and concatenate the integers. But this seems cumbersome, and I suspect that there's in built-in Julia function (or small composition of functions) that will get the job done more easily.
If your strings only use the numbers 0-9 and letters a-z and A-Z, then you can parse the string directly as base 62 BigInteger:
julia> s = randstring(123)
"RFXkzD6VpWcwvbsxOtdTxS4DGcgciKgDXECa9fEK0Djcdkcj5N75vIHEMVyuH9mcYgvFbLhbPdrKyPIO4JsK1DKgZIacov6WKDZdIpGJ5iJ15dpjmcCBCybMmxB"
julia> i = parse(BigInt, s, base=62)
12798646956721889529517502411501433963894611324020956397632780092623456213685688389093681112679380669903728068303911743800989012987014660454736389459814982802097607808640628339365945710572579898457023165244164689548286133
julia> string(i, base=62)
"RFXkzD6VpWcwvbsxOtdTxS4DGcgciKgDXECa9fEK0Djcdkcj5N75vIHEMVyuH9mcYgvFbLhbPdrKyPIO4JsK1DKgZIacov6WKDZdIpGJ5iJ15dpjmcCBCybMmxB"
I created a (somewhat complicated) implementation that works for ASCII strings:
stringToInt(str::String) = sum(i -> Int(str[end-i]) * 128^i, 0:length(str)-1)
function intToString(m::Int)
chars = Char[]
for n in div(ceil(Int, log2(x)), 7)-1:-1:0
d, m = divrem(m, 128^n)
push!(chars, d)
end
String(chars)
end
Let me know if you can think of a better one.

Extracting integer and float numbers

I have the following string "10P_57.53%_568AA". I want to extract only numbers (integer and float numbers) without any other things. The output should be like this:
10 57.53 568
Since you've not provided any language, this would be general method:
Run a loop, get each character of string in a variable say X. Compare X as if(X>=0||X<=9||X=='.'){ Concat value of X to some string }

How to reduce a String to an Integer summing its characters

I'd like to take a String e.g. "1234" and convert it to an Integer which represents the sum of all the characters.
I thought perhaps treating the String as a List of characters and doing a reduce / inject, would be the simplest mechanism. However, In all my attempts I have not managed to succeed in getting the syntax correct.
I attempted something along these lines without success.
int sum = myString.inject (0, { Integer accu, Character value ->
return accu + Character.getNumericValue(value)
})
Can you help me determine a simple syntax to resolve this problem (I can easily solve it in an java like verbose way with loops etc)
Try:
"1234".collect { it.toInteger() }.sum()
Solution by #dmahapatro
"1234".toList()*.toInteger().sum()

double.TryParse("Infinity",out dbl) return zero

I am using double.TryParse method to parse my string to double. Here in some case string might be NaN, Infinity, -Infinity. While parsing this kind of text I want double value as zero instead of double.Nan, double.Infinity. So, double.TryParse has any option to do so or need to write a method to filter this.
TryParse has no option to behave the way you desire so you will have to code it yourself. Given that Infinity and NaN are not zero, it can be no surprise that none of the built in methods return zero for those inputs.
You can parse it like that:
double value = 0;
double a = double.TryParse("YourString", out value) == true ? value : 0;
If its not double, you will get 0 else the value.

Resources