JAVA(Jcreator) final exam help!

loljustplaying

Beta member
Messages
3
Ok guys. I'm currently in high school and i have this final exam project i have to do.
Somehow, the old thread got deleted and i can't find the code anymore. This is the last part of the project.What i have to do is:

> Write a method
public static int sumDigits(int num)

The sumDigits method should calculate and return the sum of all the digits in the number that is passed to it. For example, if I call sumDigits(1234), the method should return the value 10 ( 1+2+3+4) . sumDigits does not print anything to the screen.
Then, write a simple main method to test sumDigits. It should allow the user to input a number, call the sumDigits method, and print out the result for the user to see in the format:
The sum of the digits in (number) is (answer).

Someone coded this up in C++ code... but unfortunately, i know nothing about C++...

Help coding this would be GREATLY appreciated.
 
I can quickly write something in #English and you can write to Java.

Send input -> function
Attach number to variable
Create variable i (used in loop), create variable total
Create a loop from number to 0 (in terms of i)

total =+ i

return variable to main argument
 
um... do u think u can code the whole thing? i know this may sound like a lot of work.. but i'm actually helping my friend.

Thanks so far!
 
Someone check this, I don't have JCreator set up on this computer so I haven't tried to compile:

Code:
import chn.util.*;
public class help {
    
    public static void main(String[] args) {

ConsoleIO console=new ConsoleIO();
System.out.println("Enter number:");
int oldnum=console.readInt();
int newnum=sumDigits(oldnum);
System.out.println("The sum of the digits in "+oldnum+" is "+newnum);
    }

public static int sumDigits(int num){
String A= String.valueOf(num);
int length=A.length();
int[] numArray= new int[length];
int count=0;
for(int x=0; x<=length; x++){
numArray[x]=A.charAt(x);
count=count+numArray[x];}
return count;
}
}
 
I think this is what you want. I changed the above code around to make it work.

Code:
   import java.util.Scanner;
    public class help {
    
       public static void main(String[] args) {
      
         Scanner scanner = new Scanner(System.in);
         System.out.println("Enter number:");
         int oldnum=scanner.nextInt();
         int newnum=sumDigits(oldnum);
         System.out.println("The sum of the digits in "+oldnum+" is "+newnum);
      }
   
       public static int sumDigits(int num){
         String A= String.valueOf(num);
         int length=A.length();
         int[] numArray= new int[length];
         int count=0;
         for(int x=0; x<length; x++){
            numArray[x]= Integer.parseInt(A.substring(x, x+1));
            count=count+numArray[x];
         }    
         return count;
      }
   }
 
Back
Top Bottom