The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Java Help
|
Homework - Need some help with some java code
Discuss Need some help with some java code in the Java Help forum on Dev Shed. Need some help with some java code Java Help forum discussing all Java platforms - J2ME, J2SE and J2EE - as well as relevant standards, APIs and frameworks such as Swing, Servlets, JSPs, Applets, Struts, Spring, Hibernate, ANT, EJB, and other Java-related topics.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

November 28th, 2012, 07:29 AM
|
|
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.
|

November 28th, 2012, 07:37 AM
|
 |
pollyanna
|
|
Join Date: Jul 2012
Location: Germany
|
|
|
Hi,
what are your ideas? What have you tried?
|

November 28th, 2012, 07:49 AM
|
|
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);
|

November 28th, 2012, 08:04 AM
|
 |
pollyanna
|
|
Join Date: Jul 2012
Location: Germany
|
|
|
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.
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|