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