Ask Question
25 May, 03:49

write a JAVA program that has the following methods. a. int firstDigit (int n), returning the first digit of the argument b. int lastDigit (int n), returning the last digit of the argument c. int digits (int n), returning the number of digits of the argument For example, firstDigit (1729) is 1, last digit (1729) is 9, and digits (1729) is 4. d. a main method that

+1
Answers (1)
  1. 25 May, 06:28
    0
    public class Main { public static void main (String[] args) { System. out. println (firstDigit (1729)); System. out. println (lastDigit (1729)); System. out. println (digits (1729)); } public static int firstDigit (int n) { String n_str = Integer. toString (n); char firstChar = n_str. charAt (0); String firstDigit = Character. toString (firstChar); return Integer. parseInt (firstDigit); } public static int lastDigit (int n) { String n_str = Integer. toString (n); char lastChar = n_str. charAt (n_str. length () - 1); String lastDigit = Character. toString (lastChar); return Integer. parseInt (lastDigit); } public static int digits (int n) { String n_str = Integer. toString (n); return n_str. length (); } }

    Explanation:

    Firstly we create a method firstDigit that will return the first digit of the input number (Line 8 - 13). This method will convert the input number, n, to string using Integer toString method (Line 9) and assign it to n_stry variable. Next, use charAt method with 0 index to get the first character from n_str and assign it to firstChar variable (Line 10). Next, use Character toString method to convert the firstChar to string type (Line 11) because the parseInt method which is used in Line 12 will only work on String type but not char type. The function return the firstDigit with integer type (Line 12). The parseInt method has converted the string type firstDigit to integer.

    The logical steps defined for lastDigit method are similar to firstDigit except that we need to use. length () method to get the length of the digit string and calculate the last index to get the last digit (Line 17).

    The digits method (Line 22 - 25) will convert the input number to string and then use. length () method to return the length of the number string which is equivalent of number of digit as output.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “write a JAVA program that has the following methods. a. int firstDigit (int n), returning the first digit of the argument b. int lastDigit ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers