i have a problem in a java program. :
"accept a number and print the sum of digits."
can anyone help me out???

6
Contributors
11
Replies
12
Views
8 Years
Discussion Span
Last Post by vAshunk

Break the problem down into smaller, easier to manage steps.
- Get user input
- Calculate the sum of the number(s) entered
- Print result

Show us that you have put some effort in by showing us what you have so far and we will help you from there, I, for one, will not be giving out homework answers!

Accept a number from user......
pass it in through a function call...

and then

``````public static int SumOfDigits(int x)
{
int sum = 0;
while(x > 0)
{
sum += x%10;
x /= 10;
}
return sum;
}``````

Edited by __avd: Added [code] tags. Encase your code in: [code] and [/code]

It's simple..

Just make a scanner to grab the input

Separate the digits entered using a for loop
Drop each digit into a variable

Print the result

It is simple but you also have to think of user mistakes.

Ex. user inputs 1 2 3456 asdf 234 as the input string. The letters and spaces are unwanted characters.

You will have to parse the input correctly, never assume that the user will enter what you need. For the parsing the String class has all you'll need.

So:
1)get user input.
2)parse and filter unwanted characters (a-z. A-Z, and spaces). Here you could either ignore them or throw and error informing the user of the invalid characters.
3)take the remaining digits add them
4)return the result

Hope this helps. Good luck.

i guess this is right

``````import java.util.Scanner;
class sumOfDigits
{
public void sumOfDigits()
{
int n, i ;
Scanner scnr = new Scanner(System.in);
System.out.print("enter the number :");
n = scnr.nextInt();
int sum = 0;
for (i=n; i>0;i/=10)
{
sum+=i%10;

}
System.out.println("the sum is: "+ sum);
}
}``````

Edited by __avd: Added [code] tags. Encase your code in: [code] and [/code]

how do i throw an error???

Seems about right, although I wouldn't put the user input in the sumOfDigits method. I would keep user interaction in the main function of your app. Your sum method should not have to "worry" about asking the user for input it should just process the value handed to it. Anyone have a different view on this?

Also if you leave the class name in the same case as the method the compiler will interpret it as the class constructor. If this is what your shooting for then ok just lose the void. If it isn't then I suggest using Pascal casing for the class name (SumOfDigits), but thats up to you.

You can use the throw key word for that. Also if you want to catch errors that might occur use try...catch.

Ex.

``````import java.util.Scanner;
class sumOfDigits
{
public void sumOfDigits()
{
int n, i ;

try
{
}
catch(Exception ex) //Exception class extends the Throwable class
{
//Here you would put any error handling code you would need
System.out.println("Oh snap!  You had an error: " + ex.toString(); //just an example
ex.printStackTrace();  //just another example
}
}
}``````

or

``````import java.util.Scanner;
class sumOfDigits
{
/*there are a number of exception classes look for the one you need*/
public void sumOfDigits() throws Exception
{
int n, i ;

}
}``````

If you use the second option you would have to put the call to the sumOfDigits method between a try...catch.

For more on the Exception class here, and here's more on handling exceptions in java.

Hope it helps.

i have a problem in a java program. :
"accept a number and print the sum of digits."
can anyone help me out???

Try this , I have tested it ! , I have added some error handling part also.

Please read this code line by line and try to understand each line of code, instead of copying it directly.

``````import java.util.Scanner;

class sumOfDigits
{

static int getSum(String number,int length)
{
int tmpSum=0;
for(int i=0;i<length;i++)
{
String tmpStrVal=String.valueOf(number.charAt(i));
int tmp=Integer.parseInt(tmpStrVal);
tmpSum+=tmp;
}
return tmpSum;
}

public static void main(String args[])
{
int inp,result=0;
String str;
try
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter an integer to process : ");
inp=sc.nextInt();
str=Integer.toString(inp);
result=getSum(str,str.length());
System.out.println("Sum of digits : " + result );
System.exit(0);
}
catch(Exception exp)
{
}
}
}``````

Thank you,
Kanishka Dilshan,
<FAKE SIGNATURE>

Edited by peter_budo: Keep It On The Site - Do not manually post &quot;fake&quot; signatures in your posts.

I know I probably went too far :P but here's my take on the problem.

``````import java.io.BufferedReader;
import java.io.IOException;

public class SumOfDigits{

static int sumDigits(String input){
int result = 0;

for(char j : input.toCharArray()){
result += Integer.parseInt(String.valueOf(j));
}

return result;
}

/**
* Using regular expressions looks for any characters from a-z, A-Z, and any whitespace \s.
* The \\s is done this way to avoid the invalid escape sequence that \s would throw
* @param tmp - Input string
* @return <li>true - found no whitespaces or non digit characters anywhere in the string</li>
* <li>false - found whitespaces or non digit characters anywhere in the string</li>
*/
static boolean validChar(String tmp){
boolean valid = false;

//Regular expression
String regEx = "\\s+.+|" + //starts with n whitespaces and is followed by any n characters
".+\\s+|" + //starts by any n characters and ends with n whitespaces
".+\\s+.+|" + //starts by any n characters followed by n whitespaces and ends with any n characters
"[^0-9]+.+|" + //starts with any n non digit characters and ends with any n characters
".+[^0-9]+.+|" + //starts with any n characters followed by any n non digit characters and ends with any n characters
".+[^0-9]+"; //starts with any n characters and ends with any n non digit characters

if(!tmp.matches(regEx){
valid = true;
}

return valid;
}

public static void main(String[] args){

try{
if(args.length != 0){//verify if command line args are entered
for (String i : args){ //loops through arguments
if(validChar(i)){ //verify if argument is a valid one
int result = 0;

result = sumDigits(i);
System.out.println("Total Sum: " + String.valueOf(result));
}
else{
System.out.println("An invalid character was entered.  Use only digits [0-9].");
}
}
}
else{//if no command line arguments were entered then ask for user input

System.out.print("Enter digits and press Enter: ");

if(validChar(input)){
int result = 0;

result += sumDigits(input);
System.out.println("Total Sum: " + String.valueOf(result));
}
else{
System.out.println("An invalid character was entered.  Use only digits [0-9].");
}
}
}
catch(IOException ex){
System.out.println("An IO (input/output) error ocurred: " + ex.toString());
ex.printStackTrace();
}
catch(Exception ex){
System.out.println("An unknown error ocurred: " + ex.toString());
ex.printStackTrace();
}
}
}``````

i think that i have to work a lot to level you guys...
anyway thank you a lot.
daniweb rocks

i think i have to work a lot to level you guys

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.