# Thread: I have a question regarding a simple code in JAVA

1. Member
Join Date
Apr 2014
Posts
5
Rep Power
0

## I have a question regarding a simple code in JAVA

I'm currently learning JAVA and I decided to make a little test to see my knowledge.
I wanted to write a simple code that receives information from the user (double-digit number and above) and calculates it's numbers.
For instance- The user wrote a number- 234, the software will return the number 9 (2+3+4 = 9).
Tried to use a loop for that, but I got stuck since I didn't know what to write.
I"ll be glad if you can help.

This is what I've wrote so far

Java Code:
```import java.util.Scanner;
public class Calculate {

public static void main(String[] args) {
System.out.println("Please type a number larger than 9");
Scanner type = new Scanner(System.in);
String number1 = type.nextLine();

for( int i = 0; i < number1.length(); i++ ){

int calculate = number1.charAt(i);
}
}
}```
Thanks.

2. Senior Member
Join Date
Apr 2013
Location
Sweden
Posts
272
Rep Power
8

## Re: I have a question regarding a simple code in JAVA

the charAt(..) method returns a char

You can use Character.getNumericValue(..) method to get the int value of each digit and add them in every iteration.

3. Senior Member
Join Date
Feb 2014
Posts
447
Rep Power
7

## Re: I have a question regarding a simple code in JAVA

You could also think about getting the number as an Integer instead of a String (nextInt instead of nextLine). Then you can get all digits in a loop like
while (number > 0) {
nextDigit = number % 10;
number = number / 10;
}

So with the module operation you get the first character (from right to left!) and then you divide by 10 to get the remaining characters.

Just as an alternative. (So maybe you want to try and write a method int crossSum(int number)?

With kind regards,

4. Member
Join Date
Apr 2014
Posts
5
Rep Power
0

## Re: I have a question regarding a simple code in JAVA

Originally Posted by kneitzel

You could also think about getting the number as an Integer instead of a String (nextInt instead of nextLine). Then you can get all digits in a loop like
while (number > 0) {
nextDigit = number % 10;
number = number / 10;
}

So with the module operation you get the first character (from right to left!) and then you divide by 10 to get the remaining characters.

Just as an alternative. (So maybe you want to try and write a method int crossSum(int number)?

With kind regards,

Can you write this code? I keep getting error when I use your method.

5. Member
Join Date
Apr 2014
Posts
16
Rep Power
0

## Re: I have a question regarding a simple code in JAVA

you can use this code:
public static void main(String[] args) {
System.out.println("Please type a number larger than 9");
Scanner s = new Scanner(System.in);
String line = s.nextLine();
int result = 0;

for(int i = 0; i < line.length(); i++) {
int n = line.charAt(i) - 48;
result += n;
}
System.out.println(result);
}
I think the best way is to read the line into string as you did at first, and then simply cast characters to int. You also have to subtract value 48 because charAt returns the decimal value of the character. (see asciitable)

6. Senior Member
Join Date
Feb 2014
Posts
447
Rep Power
7

## Re: I have a question regarding a simple code in JAVA

Hi,

what kind of error do you get? I just gave a short code extract that is not a method. And I didn't define any variable. But my code should work quite fine. If you want to see how it works, then you could simply modify it a little bit:

Java Code:
```		int number = 123; // Just defined the number
while (number > 0) {
System.out.print("Digit: " + number % 10); // Now I simply print out the digit!
number = number / 10;
System.out.println("  Number left: " + number);
}```
So the code is more or less the same but now you can copy & paste it to your main method if you want to play around with it.

(And maybe you try to build the method to calculate the cross number. If oyu get any error: Please tell us the error and maybe the exact code you tried. Then we can help you further.)

With kind regards,

7. Member
Join Date
Apr 2014
Posts
5
Rep Power
0

## Re: I have a question regarding a simple code in JAVA

Originally Posted by lime
you can use this code:

I think the best way is to read the line into string as you did at first, and then simply cast characters to int. You also have to subtract value 48 because charAt returns the decimal value of the character. (see asciitable)
You're right. it works great. I understand it all except the subtraction of the value 48, why did you choose 48 and how does it makes a difference?

8. Member
Join Date
Apr 2014
Posts
16
Rep Power
0

## Re: I have a question regarding a simple code in JAVA

see Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion
-look at the numeric characters with red font colour, the method charAt() returns the decimal value of the characters (it's first column) - so for number 1 it will return value 49...simply, each character has its own ascii value

9. Senior Member
Join Date
Feb 2014
Posts
447
Rep Power
7

## Re: I have a question regarding a simple code in JAVA

If you want to code it that way, then please check that it is really a number. So add a check that it is >= 48 and <= 57. If it is not, then you got an illegal input.

With kind regards,

10. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
15

## Re: I have a question regarding a simple code in JAVA

When using ASCII characters in math operations it helps to document the code better to use '0' and '9'. In addition, you don't need to remember the ASCII chart.

Regards,
Jim

11. ## Re: I have a question regarding a simple code in JAVA

Using the ascii (or unicode) code of the individual characters is clumsy; aamof using a loop is clumsy too; this little problem begs for a bit of recursion: if the number is a single digit, the result is that digit, otherwise add the rightmost digit to the result as if the rightmost digit wasn't there, i.e. C(123) == C(12)+3 = C(1)+C(2)+C(3) == 1+2+3 == 6; in code:

Java Code:
```public int C(int n) {
if (n <= 9) return n;
return n%10+C(n/10);
}```
... assuming that n >= 0.

kind regards,

Jos

12. Member
Join Date
Apr 2014
Posts
5
Rep Power
0

## Re: I have a question regarding a simple code in JAVA

Originally Posted by JosAH
Using the ascii (or unicode) code of the individual characters is clumsy; aamof using a loop is clumsy too; this little problem begs for a bit of recursion: if the number is a single digit, the result is that digit, otherwise add the rightmost digit to the result as if the rightmost digit wasn't there, i.e. C(123) == C(12)+3 = C(1)+C(2)+C(3) == 1+2+3 == 6; in code:

Java Code:
```public int C(int n) {
if (n <= 9) return n;
return n%10+C(n/10);
}```
... assuming that n >= 0.

kind regards,

Jos
Very nice,
Thanks.

Edit: why did you define the 'int n' like this: 'public int C(int n)' i.e like a class, you couldn't just wrote 'int n'?
Last edited by yakirbu; 04-21-2014 at 11:40 AM.

13. ## Re: I have a question regarding a simple code in JAVA

Originally Posted by yakirbu
Edit: why did you define the 'int n' like this: 'public int C(int n)' i.e like a class, you couldn't just wrote 'int n'?
That's not a class, it's a method named 'C' and it takes a parameter 'n' which is an int.

kind regards,

Jos

14. Senior Member
Join Date
Feb 2014
Posts
447
Rep Power
7

## Re: I have a question regarding a simple code in JAVA

Hi,

that is definition of the function. That way you get a function called C. If you just wrote something like "int n = 123" and remove the { } from the code than you get a piece of code that is doing the calculation. But you should try to keep parts of code readable and small so it is always a good thing to move such things into functions (that get a name that describes what the function is doing!).

And I am not sure what I prefer. The recursion is quite nice but I think I like the while loop more even if it has a few lines more.

So the 2 function to compare would be:
Java Code:
```	public static int crossNumber(int number) {
int result = 0;
while (number > 0) {
result += number % 10;
number = number / 10;
}
return result;
}```
Java Code:
```	public static int crossNumber(int number) {
if (number <= 9) return number;
return (number % 10) + crossNumber(number / 10);
}```
the last code is quite small but I find it harder to understand. But that is just my personal optinion and everyone else might see it different (which is completly ok!).

With kind regards,

15. Member
Join Date
Apr 2014
Posts
5
Rep Power
0

## Re: I have a question regarding a simple code in JAVA

Originally Posted by JosAH
That's not a class, it's a method named 'C' and it takes a parameter 'n' which is an int.

kind regards,

Jos
Originally Posted by kneitzel
Hi,

that is definition of the function. That way you get a function called C. If you just wrote something like "int n = 123" and remove the { } from the code than you get a piece of code that is doing the calculation. But you should try to keep parts of code readable and small so it is always a good thing to move such things into functions (that get a name that describes what the function is doing!).

And I am not sure what I prefer. The recursion is quite nice but I think I like the while loop more even if it has a few lines more.

So the 2 function to compare would be:
Java Code:
```	public static int crossNumber(int number) {
int result = 0;
while (number > 0) {
result += number % 10;
number = number / 10;
}
return result;
}```
Java Code:
```	public static int crossNumber(int number) {
if (number <= 9) return number;
return (number % 10) + crossNumber(number / 10);
}```
the last code is quite small but I find it harder to understand. But that is just my personal optinion and everyone else might see it different (which is completly ok!).

With kind regards,