Quick question , for here in the end , I try to ask user “Do you want to continue (Type y or n)”. I have user input y to be continue ,however if user input anything else the program will just exit.
What if I want this program input y to be continue ,input n to exit, but if you input anything else it will show” you need to enter the right command” and re-ask “Do you want to continue (Type y or n)”
import java.util.Scanner;
public class driver {
public static void main(String[] args){
double a = 0,b = 0,c = 0;
char ch = ‘ ‘;
do{
Scanner scanner = new Scanner(System.in);
boolean bError = true;
while (bError)
{
System.out.println(“Enter the value of a!”);
if (scanner.hasNextDouble())
{
a = scanner.nextDouble();
}
else
{
System.out.println(“Entered Non-numeric value, please enter correct value of a!”);
scanner.next();
continue;
}
bError = false;
if(a == 0)
{
bError = true;
System.out.println(“Error, Please do not enter a = 0!”);
}
}
bError = true;
while(bError)
{
System.out.println(“Enter the value of b!”);
if (scanner.hasNextDouble())
{
b = scanner.nextDouble();
}
else
{
System.out.println(“Entered Non-numeric value, please enter correct value of b!”);
scanner.next();
continue;
}
bError = false;
}
bError = true;
while(bError)
{
System.out.println(“Enter the value of c!”);
if (scanner.hasNextDouble())
{
c = scanner.nextDouble();
}
else
{
System.out.println(“Entered Non-numeric value, please enter correct value of c!”);
scanner.next();
continue;
}
bError = false;
}
if( (b*b – 4*a*c) < 0)
{
System.out.println(“Your input has no solution! please try again”);
}
else
{
double r1 = ( -b + Math.sqrt(b*b – 4*a*c) ) /(2*a);
double r2 = ( -b – Math.sqrt(b*b – 4*a*c) ) /(2*a);
System.out.println(“Root1 = “+ r1 + ” Root2 = ” + r2 + “n”);
}
System.out.print(“nDo you want to continue (Type y or n): “);
ch = scanner.next().charAt(0);
System.out.println();
} while (ch == ‘Y’ || ch == ‘y’);
System.out.print(“Bye!”);
}
}
Expert Answer
it can be done by adding another two if statements as follow
if (ch == ‘Y’ || ch == ‘y’)
{
continue;
}
else if(ch == ‘n’ || ch == ‘N’)
{
berror = false;
}
else
{
System.out.println(“enter the character for ch”);
ch = scanner.nextLine();
}