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

Will rate as lifesaver How do I add the following to my code: Throws an exceptio

ID: 3618996 • Letter: W

Question

Will rate as lifesaver

How do I add the following to my code:

Throws an exception if the user enters a nonnumeric value and asksthe user to reenter the value
Throws an exception if the user enters a grade that is not in therange 0-100 and asks the user to reenter the value



import java.util.Scanner;

public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String letter = "A";
int grade = 0 ;
int avg = 0;
System.out.println("Enter first name: ");
String first = in.next();
System.out.println("Enter last name: ");
String last = in.next();

for (int i = 0; i < 3; i++){
System.out.println("Enter grade:");
int grades = in.nextInt();
grade += grades;

}

  



}


}


Explanation / Answer

If you're throwing an exception, you generallywant the method that threw the exception to exit. So youwouldn't want to throw an exception and then ask the user tore-enter the grade. Throwing an exception: for(int i =0; i < 3; i++) { System.out.println("Entergrade: "); if(!grades.hasNextInt()) { throw newRuntimeException("Grade was not an integer."); } int grades= in.nextInt(); if(grades< 0 || grades> 100) { throw newRuntimeException("Grade must be on the interval [0, 100]."); } grade += grades; } Asking user to re-enter input: for (int i= 0; i < 3; i++) { System.out.println("Entergrade: "); int grades= 0; do { while(!in.hasNextInt()) { in.next(); System.out.print("Enter an integer: "); } grades = in.nextInt(); } while(grades< 0 || grades> 100); grade += grades; }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote