This question already has answers here:
Converting a string to int in Groovy
(13 answers)
Closed 7 years ago.
How can I convert a String (which is a number) to integer in Groovy.
I am using Groovy 2.4.5. Here is a sample code which throws exception:
Code:
def String a = "CHECK";
def String b = "3.5";
def String c = "7.5";
println "Is a number ? " + a.isNumber();
println "Is b number ? " + b.isNumber();
println "Is c number ? " + c.isNumber();
if (a.equals("CHECK"))
{
def int x = b.toInteger();
def int y = c.toInteger();
}
println b+c;
Output (with exceptions):
Is a number ? false
Is b number ? true
Is c number ? true
Exception thrown
java.lang.NumberFormatException: For input string: "3.5"
at myAdditionLogic.run(myAdditionLogic.groovy:12)
integer is a 32-bit number that doesn’t include a decimal point. You probably want a decimal data type, like Double.
Try this:
String a = "CHECK";
String b = "3.5";
String c = "7.5";
println "Is a number ? " + a.isNumber();
println "Is b number ? " + b.isNumber();
println "Is c number ? " + c.isNumber();
if (a.equals("CHECK"))
{
def x = b as Double;
def y = c as Double;
println x + y
}
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
I have a function that receives a string argument and condition inside this function that checks if this argument is int or float. Although the outcome of this condition is false, the following line is still executed.
I use PyCharm IDE and Python 3.8
Here is the code.
number1 = 17
number2 = 17.1
testStr = "Test string"
def define_type(argument01):
if type(argument01) == str:
print(argument01 + " - string")
if type(argument01) == int or float:
print(str(argument01) + " - int or float")
define_type(testStr)
The output:
Test string - string
Test string - int or float
Process finished with exit code 0
if type(argument01) == int or float:
can be rewritten
if (type(argument01) == int) or float:
so even argument01 is not an int the test is always true, in a way your test is
if float:
You want :
if type(argument01) == int or type(argument01) == float:
I am trying to get a date from this text:
{InstantSeconds=1581504140},ISO,Europe/Paris resolved to 2020-02-12T11:42:20
I tried doing
def text = "{InstantSeconds=1581504140},ISO,Europe/Paris resolved to 2020-02-12T11:42:20"
text = text.replaceAll("[^\\d.]", "")
text = text.substring(10)
println "${text}"
int result= Integer.parseInt("${text}");
println result
But I'm getting
java.lang.NumberFormatException: For input string: "20200212114220"
I'm using this (for practice) https://groovyconsole.appspot.com/
Does anyone know why that happens?
The value is too long for an integer. Use a Long datatype:
Long result = text.toLong()
assert result.class.name == 'java.lang.Long'
assert result == 20200212114220
I need to truncate a text to get a preview. The preview is the text prefix of ~N chars (but not more) and it should not split words in the middle.
preview("aaa", 10) = "aaa"
preview("a b c", 10) = "a b c"
preview("aaa bbb", 5) = "aaa"
preview("a b ccc", 3) = "a b"
I coded a function as follows:
def preview(s:String, n:Int) =
if (s.length <= n) s else s.take(s.lastIndexOf(' ', n))
Would you change or fix it ?
Now I am thinking how to handle the case when the text words are separated by one or more white spaces (including \n,\t, etc.) rather than just a single space. How would you improve the function to handle this case ?
How about the following:
def preview(s: String, n: Int) = if (s.length <= n) {
s
} else {
s.take(s.lastIndexWhere(_.isSpaceChar, n + 1)).trim
}
This function will:
For the strings shorter or equal n return the string (no preview required)
Otherwise find the the last space character in the n + 1 first characters (this will indicate whether the last world is being split, as if it's not than n + 1 will be a space chracter and otherwise a non-space character) and take a string up to this point
Note: The usage of isSpaceChar will not only provide support for space, but also new line or paragraph, which is what I believe you're after (and you can replace it with isWhitespace if you're after even more extended set of word separators).
I propose next one:
-- UPDATED--
def ellipsize(text : String, max : Int): String = {
def ellipsize0(s : String): String =
if(s.length <= max) s
else {
val end = s.lastIndexOf(" ")
if(end == -1) s.take(max)
else ellipsize0(s.take(end))
}
ellipsize0("\\s+".r.replaceAllIn(text, " "))
}
Or your (modified):
def preview(str : String, n : Int) = {
(s : String) => if (s.length <= n) s else s.take(s.lastIndexOf(' ', n))
}.apply( "\\s+".r.replaceAllIn(str, " "))
How about this
def preview(s:String, n:Int) =
if (s.length <= n) s
else s.take(n).takeWhile(_ != ' ')
Try it here: http://scalafiddle.net/console/a05d886123a54de3ca4b0985b718fb9b
This seems to work:
// find the last word that is not split by n, then take to its end
def preview(text: String, n: Int): String =
text take (("""\S+""".r findAllMatchIn text takeWhile (_.end <= n)).toList match {
case Nil => n
case ms => ms.last.end
})
An alternative take (pun intended) but doesn't like input of all whitespace:
text take (("""\S+""".r findAllMatchIn text takeWhile (m => m.start == 0 || m.end <= n)).toList.last.end min n)
Extensionally:
object Previewer {
implicit class `string preview`(val text: String) extends AnyVal {
// find the last word that is not split by n, then take to its end
def preview(n: Int): String =
text take (("""\S+""".r findAllMatchIn text takeWhile (_.end <= n)).toList match {
case Nil => n
case ms => ms.last.end
})
}
}
Looks nice that way:
class PreviewTest {
import Previewer._
#Test def shorter(): Unit = {
assertEquals("aaa", "aaa" preview 10)
}
#Test def spacey(): Unit = {
assertEquals("a b c", "a b c" preview 10)
}
#Test def split(): Unit = {
assertEquals("abc", "abc cba" preview 5)
}
#Test def onspace(): Unit = {
assertEquals("a b", "a b cde" preview 3)
}
#Test def trimming(): Unit = {
assertEquals("a b", "a b cde" preview 5)
}
#Test def none(): Unit = {
assertEquals(" " * 5, " " * 8 preview 5)
}
#Test def prefix(): Unit = {
assertEquals("a" * 5, "a" * 10 preview 5)
}
}
I have an arraylist consisting of decimal numbers and i m supposed to take the average of last 4 elements of this arraylist.And these rational number are type of String.
private void average(String confidence) {
if(myList.size() >= 4) {
String t = myList.get(myList.size()-1);
String d = myList.get(myList.size()-2);
String f = myList.get(myList.size()-3);
String h = myList.get(myList.size()-4);
String s = (t + d + f+h) ;
long fin = Long.parseLong(s);
long result = fin/4 ;
System.out.println("Average is: "+result);
}
but this method does not work.Could you please tell me what kind of changes am i supposed to do or any advices of doing this? Thanks a lot in advance!!!
Your issue is the String s = (t + d + f+h) part. You're just appending 4 Strings right now.
You need to convert them first.
And your result will be wrong, you need to divide by 4, not 3.
Colleen's answer is good, so long as you remember to change the type to reflect what Long.parseLong() returns. I'd reply, but I'm too new.
if(myList.size() >= 4) {
Double t = Double.parseLong(myList.get(conf.size()-1));
Double d = Double.pareseLong(myList.get(conf.size()-2));
Double f = Double.parseLong(myList.get(conf.size()-3));
Double h = Double.parseLong(myList.get(conf.size()-4));
Double result = (t + d + f + h) / 3 ;
System.out.println("meanAsrConfidence is: "+result);
}
You need to convert before you add. + on Strings means concatenate.
if(myList.size() >= 4) {
//I'm guessing all of these conf.size() calls are meant to be myList.size()
double t = Double.parseDouble(myList.get(conf.size()-1));
double d = Double.pareseDouble(myList.get(conf.size()-2));
double f = Double.parseDouble(myList.get(conf.size()-3));
double h = Double.parseDoublemyList.get(conf.size()-4));
double s = (t + d + f+h) ;
double result = s/3 ; //should be 4
System.out.println("meanAsrConfidence is: "+result);
}
What you are doing now is, for example:
t=1, d=2, f=3, h=4
s = 1234
Also:
you need to divide by 4, not 3
what is conf? Why are you not calling myList.size()?
you're passing a String as an argument when you probably want to be passing myList
How do I find the indexes of all the occurances of a substring in a large string -
(so basically ,and extension of the "indexOf" function) . Any ideas?
Current situation:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexOf(sub)
// = 9
I want something like:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
// = [9,15]
Is there such a function? How should I implement it otherwise? (in a non trivial way)
You could write a new addition to the String metaClass like so:
String.metaClass.indexesOf = { match ->
def ret = []
def idx = -1
while( ( idx = delegate.indexOf( match, idx + 1 ) ) > -1 ) {
ret << idx
}
ret
}
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
There is nothing I know of that exists in groovy currently that gets you this for free though
This is a relatively easy approach:
String.metaClass.indexesOf = { arg ->
def result = []
int index = delegate.indexOf(arg)
while (index != -1) {
result.add(index);
index = delegate.indexOf(arg, index+1);
}
return result;
}
Note that this will find overlapping instances (i.e. "fooo".indexesOf("oo") will return [1, 2]). If you don't want this, replace index+1 with index+arg.length().