Answer the question
In order to leave comments, you need to log in
Extract numbers from a string and find their sum in java?
there is a line, for example, "Vasya earned 5000 rubles, Petya - 7563 rubles, and Masha - 30000". The output should give the sum of all the numbers in the string. I extracted numbers from a string, but I don't understand how to add them. Regular expressions cannot be used
String str = text.trim();
String digits="";
for (int i = 0; i < str.length(); i++) {
char chrs = str.charAt(i);
if (Character.isDigit(chrs))
digits = digits+chrs;
}
System.out.println(digits);
Answer the question
In order to leave comments, you need to log in
Since regular expressions cannot be used, write a state machine. There will be only a couple of states (reading a number (D), reading not a number (C)) and transitions between them.
Initially, it is in state C.
Being in state C, we see a digit - go to state D, and write the digit to the buffer, go to the next character. Being in state C and seeing a non-digit, stay in C and move on to the next character.
Being in state D and seeing a number, we remain in D and append the number to the buffer. Being in state D and seeing a non-digit, we go to state C, add the buffer to the sum, clear the buffer.
The buffer can be immediately a number, then adding to it means buffer = buffer*10+d, and clearing means assigning zero.
String str = text.trim();
String digits="";
int sum = 0;
str+=" ";
for (int i = 0; i < str.length(); i++) {
char chrs = str.charAt(i);
if (Character.isDigit(chrs))
digits+=chrs;
else{
if(!digits.equals(""))
sum+= Integer.parseInt(digits);
digits = "";
}
}
System.out.println(sum);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question