Submit Chapter5.java with \" public static\" methods for solutions of these Exer
ID: 3760479 • 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
// Please note I calculated range of value of digits as (Max digit-Min Digit +1).
import java.util.Scanner;
public class sample
{
public static int digitSum(int x)
{
int sum=0;
while(x>0)
{
sum=sum+x%10;
x=x/10;
}
return sum;
}
public static int digitRange(int x)
{
int digit;
int min = 10;
int max = -1;
while( x > 0 ) {
digit = x%10;
x /= 10;
min = Math.min(min,digit);
max = Math.max(max,digit);
}
return max-min+1;
}
public static String randColor()
{
// Here i use random Number generator to generate random Color.
int r = (int) (Math.random() * (3 - 0)) + 0;
String color=" ";
if(r==0)
color="red";
else if(r==1)
color="blue";
else
color="yellow";
return color;
}
public static boolean isValidHex(String hex)
{
int len=hex.length();
int count=0;
for(int i=0;i<len;i++)
{
if((hex.charAt(i)>='A'&& hex.charAt(i)<='F') ||(hex.charAt(i)>='a'&& hex.charAt(i)<='f')||(Integer.parseInt(String.valueOf(hex.charAt(i)))>=0 && Integer.parseInt(String.valueOf(hex.charAt(i)))<=9))
{
count++;
}
}
if(count==len)
return true;
else
return false;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("input integer value");
int input=sc.nextInt();
System.out.println("input String value");
String hex=sc.next();
System.out.println("Sum of digits of number "+digitSum(input));
System.out.println("Range of value of digits "+digitRange(input));
System.out.println("The Random Color is "+randColor());
System.out.println("The Entered String is Hex "+isValidHex(hex));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.