213k views
2 votes
Modify any of the previous labs which would have crashed when non-numeric data was entered by adding exception handling so that the non-numeric input no longer crashes the program. The program must handle the invalid input gracefully by informing the user of the bad input and re-querying until the user provides valid input. It must re-query for the specific input which was incorrectly entered.

User Jurglic
by
4.0k points

1 Answer

3 votes

Answer:

see explaination

Step-by-step explanation:

import java.util.InputMismatchException;

import java.util.Scanner;

public class calculate {

static float a=0,b=0;

double cal()

{

if(a==0||b==0)

{

System.out.println("no values found in a or b");

start();

}

double x=(a*a)+(b*b);

double h=Math.sqrt(x);

a=0;

b=0;

return h;

}

float enter()

{

float val=0;

try

{

System.out.println("Enter side");

Scanner sc1 = new Scanner(System.in);

val = sc1.nextFloat();

return val;

}

catch(InputMismatchException e)

{

System.out.println("Enter correct value");

}

return val;

}

void start()

{

calculate c=new calculate();

while(true)

{

System.out.println("Enter Command");

Scanner sc = new Scanner(System.in);

String input = sc.nextLine();

switch(input)

{

case "A":

a=c.enter();

break;

case "B":

b=c.enter();

break;

case "C":

double res=c.cal();

System.out.println("Hypotenuse is : "+res);

break;

case "Q":

System.exit(0);

default:System.out.println("wrong command");

}

}

}

public static void main(String[] args) {

calculate c=new calculate();

c.start();

}

}

User Ramchandra N
by
4.0k points