This is the complete solution to find the sum of digits from a given number using the String class, and a few methods. This solution covers all validations. Regular expressions are also used in this solution for validating the given input.
import java.util.Scanner;
public class SumOfDigitsInNumber {
public static void main(String[] args) {
Scanner inpStr = new Scanner(System.in);
System.out.println("Enter a number");
String inpLine = inpStr.nextLine();
/*
* Basic validations - Checking if the input number is empty or if it contains
* more than one number, or if it's purely numeric (no alphabets or symbols).
*/
if (inpLine.isEmpty())
System.out.println("Given number is empty");
else if (inpLine.split("\\s").length > 1)
System.out.println("Input can only contain one number");
else if (!isValidInput(inpLine))
System.out.println("The input should be a number");
else {
inpStr.close();
System.out.printf("The sum of all the digits in the number is %d", sumOfDigits(inpLine)).println();
}
}
private static boolean isValidInput(String s) {
/*
* This method uses regular expressions to check if the input number is valid by
* checking if it only contains digits and returning true if it does.
*/
if (s.matches("[0-9]*$") && s.matches("[^a-zA-Z]*$"))
return true;
else
return false;
}
private static int sumOfDigits(String s) {
/*
* This method runs through the input string and adds up every single digit to a
* variable which is returned at the end
*/
int digitAdder = 0;
try {
for (int i = 0; i < s.length(); i++) {
digitAdder += ((int) s.charAt(i) - 48); // ASCII value
}
} catch (Exception e) {
System.out.printf("Exception is %s", e).println();
}
return digitAdder;
}
}
Output:
Enter a number
5612
The sum of all the digits in the number is 14
Enter a number
Hello@123
The input should be a number

Leave a comment