Java Program: (name this Lab14_Problem6) Modify Problem 4 such that the value on
ID: 3769842 • Letter: J
Question
Java Program: (name this Lab14_Problem6)
Modify Problem 4 such that the value on which the method operates is provided by the end user. Key design factors:
In main(), prompt the use for a value between 1 and 20.
Validate the input to ensure it's an integer. Use a try-catch block to do this. Your trigger (first statement in the try block) should be something like this: iVal = cin.nextInt();
The error to catch is InputMismatchException.
If caught, display Error: not an int and end the program.
If the user types an int, then inside the try validate that is in the range of 1 to 20. Anything outside of the range, display Error: not in range 1 to 20 and end the program.
Finally, if the user's entry is in range, then call the method to calculate the sum of the digits recursively. Return the sum of the digits to main() for display.
Explanation / Answer
package current;
import java.util.InputMismatchException;
import java.util.Scanner;
public class IntegerSumTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
try {
System.out.println("Enter an integer value from 1 to 20:");
int num = scan.nextInt();
if(num <1 || num > 20)
System.out.println("Error: not in range 1 to 20");
else {
//total
System.out.println("Sum of the digits form 1 to "+num+" is "+IntegerSumTest.sum(num));
}
} catch(InputMismatchException e) {
System.out.println("Error: Not an int value");
}
}
public static int sum(int n) {
if(n == 1)
return 1;
else
return n+sum(n-1);
}
}
------------output--------------
Enter an integer value from 1 to 20:
6
Sum of the digits form 1 to 6 is 21
Enter an integer value from 1 to 20:
8.6
Error: Not an int value
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.