3) Write a static method and a test program for a method called digitRange() tha
ID: 3729836 • Letter: 3
Question
3) Write a static method and a test program for a method called digitRange() that takes an integer n as an argument and returns the largest difference between the individual digits in the number. For example the call digitRange(68437) should return 5 because the largest difference between individual digits is (8 - 3). You should test whether the number passed to the method is >= 0 and throw an IllegalArgumentException if not. Passing a 1 digit number should return a 0 (zero). You must test these cases: Method Call Value Returned digitRange(0) 0 digitRange(26) 4 digitRange(42) 2 digitRange(888) 0 digitRange(1234) 3 digitRange(24680) 8 digitRange(857492) 7 You can use any techniques you want, including Strings to inspect the individual digits. (25 pts) To get full credit, you must show the 7 test values defined above
Explanation / Answer
public class Main
{
public static void main(String[] args) {
int difference=digitRange(857492);
System.out.println(difference);
}
public static int digitRange(int range)
{
int max=0;
int min=0;
int digit=0;
if(range<0)
throw new IllegalArgumentException();
int count=0;
while(range!=0)
{
digit=range%10;
range=range/10;
if(count==0)
{
max=digit;
min=digit;
}
else
{
if(digit>=max)
max=digit;
else if(digit<=min)
min=digit;
}
count++;
}
return max-min;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.