November 28th, 2012, 07:29 AM
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
what are your ideas? What have you tried?
November 28th, 2012, 07:49 AM
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
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.