Submit Chapter5.java with \" public static\" methods for solutions of these Exer
ID: 3760421 • 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
public static int digitRange(int a){
int min = Integer.MAX_VALUE;
int max = 0,temp;
if(a < 0)
a = -a;
while(a > 0){
temp = a %10;
if(temp > max)
max = temp;
if(temp < min)
min = temp;
a = a/10;
}
return max - min + 1;
}
public static int digitSum(int a){
int sum = 0;
if(a < 0)
a = -a;
while(a > 0){
sum += a %10;
a = a/10;
}
return sum;
}