Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Submit Chapter5.java with \" public static\" methods for solutions of these Exer

ID: 3760508 • Letter: S

Question

Submit Chapter5.java with "public static" methods for solutions of these Exercises starting on page 381:

A. Exercise #18: digitSum, do not use String

write a method called digitSum that accepts an integer as a parameter and returns the sum of the digits of that number.

B. Exercise #20: digitRange, do not use String

write a mthod called digitRange that accepts a integer as a parameter and returns the range of values of its digits.

C. Write a method randColor() that returns a String which will randomly be one of the three primary colors ("red" or "yellow" or "blue").

D. Write a boolean method isValidHex that determines if a single String parameter contains only hexadecimal digits (0-9, a-f, A-F). For example, returns true, isValidHex("A932B") returns true, and isValidHex("anythingElse") returns false.   Your method cannot throw exceptions and must use an if-else block.

Explanation / Answer

import java.util.Random;

public class Chapter5 {

public static int digitSum(int n) {

       int sum=0;

       while (n!=0) {

           sum+=n%10;

           n=n/10;

       }

       return sum;

   }

  

   public static int[] digitRange(int n) {

       int min=n%10;

       int max=n%10;

       n=n/10;

      

       while (n!=0) {

           int temp = n%10;

           if (temp < min) {

               min = temp;

           }

           if (temp > max) {

               max = temp;

           }

           n=n/10;

       }

       int[] range = new int[2];

       range[0] = min;

       range[1] = max;

       return range;

   }

  

   public static String randColor() {

       Random r = new Random();

       int c = r.nextInt(3);

       return (c == 0 ? "Red" : (c == 1 ? "Yellow" : "Blue"));

   }

  

   public static boolean isValidHex(String hex) {

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

           if (!((hex.charAt(i) >= 'a' && hex.charAt(i) <= 'f') ||

                   (hex.charAt(i) >= 'A' && hex.charAt(i) <= 'F') ||

                   (hex.charAt(i) >= '0' && hex.charAt(i) <= '9'))) {

               return false;

           }

       }

       return true;

   }

  

   public static void main(String[] args) {

       System.out.println(digitSum(1234));

   }

}