Read the value from the format string Java, groovy

I want to know how to read a single attribute from a formatted string in groovy or even Java

I have a string containing properties separated by spaces For example, "2.1 20 something true" The order is fixed and the "attribute type" is known (for example, first float, second integer, etc.) I need something like string Format(), but vice versa

I know I can manually split the string and read the value, but this will make the code too complex, as shown below:

String[] parsedText = "2.1 20 Something true".split(delimiter)

try {
   firstVal = new Float(parsedText[0])
}
catch (NumberFormatException e) {
   throw new RuntimeException("Bad data [0th position in data string],cannot read[{$parsedData[0]}],cannot convert to float")
}
...

Is there a better way? I'm pretty sure, at least in groovy: -)

thank you!

Solution

The Java scanner class has a lot of methods to grab and parse the next part of the string, such as next(), nextint(), nextdouble(), etc

The code is as follows:

String input = "2.1 20 Something true";
Scanner s = new Scanner(input);
float f = s.nextFloat();
int i = s.nextInt();
String str = s.next(); // next() doesn't parse,you automatically get a string
boolean b = s.nextBoolean();

The only thing to be vigilant about is that both next () and nextline () can get strings, but next () can only get the string of the next space If you want to include spaces in the string component, you need to consider this

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>