Reputation: 333
Help me please for the next problem:
There is String pattern, assume it's public final static variable. There is string where we search. There is class, simple wrapper to double
public class Wrapper {
private double value;
public double getValue() {
return value;
}
public Wrapper(double value) {
this.value = value;
}
}
I need method
public Wrapper parse(String s, int index)
which returns Wrapper's object if string at the index is double number with maximum 2 digits after decimal point(if there is decimal point at all) and right after number ends there is String pattern after it For example for strings
String pattern = "money";
String search = "Giveme10.25moneyplease";
parse(search, 6) returns new Wrapper(10.25)
In other cases (index less then zero, greater then length of the string, substring that starts from index isn't number at all or it's double number but it contains more then 2 digits after decimal point or there is no string pattern after number) method must return null
And another method that differs only string pattern must be first and then double number with maximum 2 digits after decimal point and all other the same
String pattern = "money"
String s = "Ihavemoney10.50"
parse1(s, 5) returns new Wrapper(10.50)
Upvotes: 0
Views: 703
Reputation: 15718
You can use DecimalFormat
along with ParsePosition
like this
import java.text.DecimalFormat;
import java.text.ParsePosition;
public class TestP {
public static void main(String[] args) {
DecimalFormat decimalFormat = new DecimalFormat("00.##'money'");
String search = "Giveme10.25moneyplease";
int index = 6;
//output 10.25
Number number = decimalFormat.parse(search, new ParsePosition(index));
if (number != null) {
String s = number.toString();
if (s.contains(".") && s.length() > 5) {
number = null;
}
}
System.out.println(number);
}
}
Upvotes: 2