Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

#1
November 28th, 2012, 07:29 AM
 joconnor1981
Registered User

Join Date: Nov 2012
Posts: 2
Time spent in forums: 1 h 28 m 23 sec
Reputation Power: 0
Homework - Need some help with some java code

I got this Question for an exam due Friday any help would be appreciated. Thanks.

Write the following methods and provide a program to test them.
public int firstDigit(int n), returning the first digit of the argument.
public int lastDigit(int n), returning the last digit of the argument.
public int digits(int n), returning the number of digits of the argument.
For example, firstDigit(1729) is 1, lastDigit(1729) is 9, and digits(1729) is 4.

#2
November 28th, 2012, 07:37 AM
 Jacques1
pollyanna

Join Date: Jul 2012
Location: Germany
Posts: 1,881
Time spent in forums: 1 Month 2 Weeks 2 Days 8 h 22 m
Reputation Power: 813
Hi,

what are your ideas? What have you tried?

#3
November 28th, 2012, 07:49 AM
 joconnor1981
Registered User

Join Date: Nov 2012
Posts: 2
Time spent in forums: 1 h 28 m 23 sec
Reputation Power: 0
Was thinking something like this but not sure???

int number = 15;
int lastDigit = number%10;
int firstDigit = number/10;
System.out.println(lastDigit + firstDigit);

#4
November 28th, 2012, 08:04 AM
 Jacques1
pollyanna

Join Date: Jul 2012
Location: Germany
Posts: 1,881
Time spent in forums: 1 Month 2 Weeks 2 Days 8 h 22 m
Reputation Power: 813
The last digit is correct, but the first digit only works on two digit numbers. For example, 123 / 10 will be 12.

But you can still use this approach. You just have to repeat "cutting off" the last digit until the number has only one digit. This can be done with a loop or with recursion.

You have to be careful with negative numbers, though.

Another approach for this task would be to convert the integers into strings and simply use string functions to get the first character, count the length etc. But I don't think that's what you're supposed to do.

 Viewing: Dev Shed Forums > Programming Languages > Java Help > Homework - Need some help with some java code