JAVA program to return the sum of numbers appearing in a string import java.util.Scanner; public class sum{ static int sumNumbers(String str) { String temp = "0"; int sum = 0; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (Character.isDigit(ch)) temp += ch; else { sum += Integer.parseInt(temp); temp = "0"; } } return sum + Integer.parseInt(temp); } public static void main(String[] args) { Scanner sc= new Scanner(System.in); System.out.print("Enter a string: "); String str= sc.nextLine(); System.out.print("You have entered: "+sumNumbers(str)); } } This is my java code. I am not able to compile it to get input from user and display sum of digits appearing in a string. Please show implementation with correct output sample output sumNumbers("abc123xyz") → 123 sumNumbers("aa11b33") → 44 sumNumbers("7 11") → 18
JAVA program to return the sum of numbers appearing in a string
import java.util.Scanner;
public class sum{
static int sumNumbers(String str)
{
String temp = "0";
int sum = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isDigit(ch))
temp += ch;
else {
sum += Integer.parseInt(temp);
temp = "0";
}
}
return sum + Integer.parseInt(temp);
}
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.print("Enter a string: ");
String str= sc.nextLine();
System.out.print("You have entered: "+sumNumbers(str));
}
}
This is my java code. I am not able to compile it to get input from user and display sum of digits appearing in a string.
Please show implementation with correct output
sample output
sumNumbers("abc123xyz") → 123
sumNumbers("aa11b33") → 44
sumNumbers("7 11") → 18
Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 3 images
- Recommended textbooks for youDatabase System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSONDatabase System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSONC How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag…Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education