Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Digits {
- public static double getDigits(String s){
- double sum = 0;
- String temp = "";
- CharSequence seq = ".";
- for (int i = 0; i < s.length(); i++) {
- if((Character.isDigit(s.charAt(i)) || s.charAt(i) == '.') && i!=s.length()-1){
- if(temp=="" && s.charAt(i) == '.'){
- continue;
- } else if(temp.contains(seq) && s.charAt(i) == '.') throw new NumberFormatException("Unformatted Input");
- // this check makes the algorithm O(n^2) in the worst possible case, otherwise it is O(n)
- // it is not O(n(nm)) (Boyer-Moore) , because the char sequence is only '.'
- temp+=s.charAt(i);
- } else {
- if(Character.isDigit(s.charAt(i)) && i==s.length()-1) temp+=s.charAt(i);
- try{sum+=Double.parseDouble(temp);}
- catch(Exception e){}
- temp="";
- }
- }
- return sum;
- }
- public static void main(String[] args){
- String s = "2 beers0.5 or not 12.3 beers.5";
- try{
- System.out.println(getDigits(s));
- } catch(Exception e){
- System.out.println(e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement