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

B) Rewrite the part of the program so that if the user inputs an improper format

ID: 3627818 • Letter: B

Question

B) Rewrite the part of the program so that if the user inputs an
improper format for either numerator or denominator, the entire input query
repeats until both formats are OK. Hint: Put "try" and "catch" blocks in a loop that
executes "while" (OK == false), and set OK = true after all the critical operations in
the "try" block have succeeded. Note: If the scanned format is bad, you'll get
infinite looping unless you re-instantiate "stdIn in each iteration, or use a two-step
operation for each input(input a string and then parse it)


import java.util.Scanner;
public class Division2
{
public static void main (String[] args)
{
Scanner stdIn = new Scanner(System.in);
double n;
int d;

System.out.print("Enter numerator: ");
n = stdIn.nextDouble();
System.out.print("Enter divisor: ");
d = stdIn.nextInt();
System.out.println(n / d);
}// end main
} end Division2 class

Explanation / Answer

import java.math.*;

import java.util.Scanner;

public class Diviser5

{

public static void main(String[] args)

{

Scanner stdIn = new Scanner(System.in);

double n;

int d;

boolean OK=true;

//Loop repeats untill valid values are entered

do

{

System.out.print("Enter numerator: ");

n = stdIn.nextDouble();

System.out.print("Enter divisor: ");

d = stdIn.nextInt();

if(d==0)

OK=false;

else

OK=true;

}while(OK==false);

//display output

System.out.println("Result:"+n/d);

}

}

Enter numerator: 4.0

Enter divisor: 0

Enter numerator: 4.2

Enter divisor: 2

Result:2.1