I am having an issue where it isn't checking the validity of user input correctly. It breaks if I input a letter or string as a choice instead of looping through and asking again. I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement. Advice?
public class Main
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
displayMenu();
int entryChoice = scan.nextInt();
while (entryChoice != 9)
{
System.out.println(userSelection(entryChoice));
displayMenu();
isInt(entryChoice);
entryChoice = scan.nextInt();
}
scan.close();
System.exit(0);
}
public static boolean isDouble(double x)
{
double userInput = x;
try
{
userInput = Double.parseDouble(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input. Try again.");
return false;
}
}
public static boolean isInt(int x)
{
int userInput = x;
try
{
userInput = Integer.parseInt(scan.next());
return true;
}
catch (NumberFormatException ignore)
{
System.out.println("Invalid input");
return false;
}
}
public static void displayMenu()
{
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice)
{
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6)
{
System.out.println("Enter one number: ");
x = scan.nextDouble();
}
else
{
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
}
switch (entryChoice)
{
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0)
{
System.out.println("Can't divide by zero. Please enter another number.");
y = scan.nextDouble();
result = x / y;
}
else
{
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
//store a number
break;
case 8:
//recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}
I'm pretty sure that I have my functions, isDouble and isInt, correct and it's more a matter of placement.
You don't.
Your isInt() method ignores its parameter, reads a new value from the scanner and checks to see if it's a number, and doesn't return the new value, whether or not it's a number.
In any case, the Scanner class you are using to collect user input already does this sort of validation for you. You started in the correct direction with
int entryChoice = scan.nextInt();
but it's dangerous to try to get a token from a Scanner without first checking to see if it has one for you to get.
If you look at the API docs for Scanner, you'll see a whole list of nextFoo() and hasNextFoo() methods. These are meant to be used together.
Generally what you want is a loop which prompts the user for the desired input until they give it, like this:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number");
while (!scan.hasNextInt()) {
scan.next(); // throw away non-numeric input
System.out.println("Please enter a number");
}
System.out.println("User entered: " + scan.nextInt());
This will end up re-prompting the user until they give you a number:
Please enter a number
apple
Please enter a number
fox
Please enter a number
bear
Please enter a number
42
User entered: 42
Here is your code,However i did many changes.Wish this help you little.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
static Scanner scan = new Scanner(System.in);
static int entryChoice = 0;
static boolean tester = true;
static double result;
public static void main(String[] args) {
displayMenu();
boolean check = isInt(entryChoice);
while (check && entryChoice != 9) {
result = userSelection(entryChoice);
System.out.print(result == 0 && !tester ? "" : result + "\n");
if (!tester)
break;
}
scan.close();
System.exit(0);
}
/*
* public static boolean isDouble(double x) {
*
* try { x = Double.parseDouble(scan.next()); return true; } catch
* (NumberFormatException ignore) { System.out.println(
* "Invalid input. Try again.");
*
* return false; } }
*/
public static boolean isInt(int x) {
try {
x = Integer.parseInt(scan.next());
entryChoice = x;
return true;
} catch (NumberFormatException ignore) {
System.out.println("Invalid input");
System.err.println("program will be terminated!");
tester = false;
return false;
}
}
public static void displayMenu() {
System.out.println("Please select from the following choices:");
System.out.println();
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("5) Raise to a Power");
System.out.println("6) Square Root");
System.out.println("7) Store a Number");
System.out.println("8) Recall Stored Number");
System.out.println("9) Exit Program");
System.out.println();
System.out.println("Enter your choice here: ");
}
public static double userSelection(int entryChoice) {
double result = 0;
double x = 0;
double y = 0;
if (entryChoice == 6) {
try {
System.out.println("Enter one number: ");
x = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.out.println("Invalid input");
}
} else {
try {
System.out.println("Enter two numbers seperated by a space");
x = scan.nextDouble();
y = scan.nextDouble();
} catch (InputMismatchException ignore) {
System.err.println("Invalid input,program will be terminated !");
tester = false;
// return ;
}
}
switch (entryChoice) {
case 1:
result = x + y;
break;
case 2:
result = x - y;
break;
case 3:
result = x * y;
break;
case 4:
if (y == 0 && tester) {
System.out.println("Can't divide by zero. Please enter another number.");
try {
y = scan.nextDouble();
} catch (InputMismatchException ex) {
System.err.println("invalid input, program will be terminated");
tester = false;
}
result = x / y;
} else if (tester) {
result = x / y;
}
break;
case 5:
result = Math.pow(x, y);
break;
case 6:
result = Math.sqrt(x);
break;
case 7:
// store a number
break;
case 8:
// recall a stored number
break;
case 9:
result = 0;
break;
default:
}
return result;
}
}
Related
My program runs but when I need it to calculate what I need it to do (add, subtract, multiply, divide) it just puts in the value that I typed in and won't do the operation I tell it to do, it just displays the menu again. How do I fix it so it can do the function it needs to do and also loop back to the menu to do another function? (ex. I want to add 2 and 2 together then turn around and multiply 3 and 2)
public static void main(String[] args) {
Testt calc = new Testt();
calc.getCurrentValue();
displayMenu();
}
public static int displayMenu() {
Scanner input = new Scanner(System.in);
Testt calc = new Testt();
int choice;
do {
System.out.println("Hello, welcome to the menu");
System.out.println("Select one of the following items from the menu:");
System.out.println("1) Add ");
System.out.println("2) Subtract ");
System.out.println("3) Multiply ");
System.out.println("4) Divide ");
System.out.println("5) Clear ");
System.out.println("6.Quit");
System.out.println ("Please choice an option from the menu:");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
return displayMenu();
}
} while (choice > 6 && choice < 1);
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
return choice;
}
public static double getOperand(String prompt) {
return 0;
}
private double currentValue;
public double getCurrentValue() {
System.out.println("The current value is " + currentValue);
return 0;
}
public void add(double operand2) {
currentValue = currentValue + operand2;
getCurrentValue();
}
public void subtract(double operand2) {
currentValue = operand2 - currentValue;
getCurrentValue();
}
public void multiply(double operand2) {
currentValue = operand2 * currentValue;
getCurrentValue();
}
public void divide(double operand2) {
if (operand2 == 0) {
System.out.println("Sorry, you can not divide by 0");
}
currentValue = operand2 / currentValue;
getCurrentValue();
}
public void clear() {
currentValue = 0;
getCurrentValue();
}
From getCurrentValue() you are always returning 0.
You need to return current value.
Also if you want to loop back to same thing you can put all this in while(true) loop. like this:
public static int displayMenu() {
Scanner input = new Scanner(System.in);
Demo calc = new Demo();
int choice;
System.out.println("Hello, welcome to the menu");
System.out.println("Select one of the following items from the menu:");
System.out.println("1) Add ");
System.out.println("2) Subtract ");
System.out.println("3) Multiply ");
System.out.println("4) Divide ");
System.out.println("5) Clear ");
System.out.println("6.Quit");
while(true){
System.out.println ("Please choice an option from the menu:");
choice = input.nextInt();
if (choice > 6 || choice < 1) {
System.out.println("Sorry," + choice + " was not an option");
continue;
}
if (choice == 5) {
calc.clear();
return 0;
} else if (choice == 6) {
System.out.println("Goodbye! ");
System.exit(0);
}
System.out.println("What is the second number? ");
double operand2 = input.nextDouble();
switch (choice) {
case 1:
calc.add(operand2);
break;
case 2:
calc.subtract(operand2);
break;
case 3:
calc.multiply(operand2);
break;
case 4:
calc.divide(operand2);
break;
}
}
}
edit:
adding the one of the methods called below, just in case the problem is with the method, not the loop.
Below is a switch menu, there are several cases in the switch. Each case calls a a public void method form another class, and completes successfully, is supposed to displays the menu method (method that prints menu options) and allow the user to select another option. Currently, after completing one case, the program showMenu() again, then breaks at instantly:
String menu = in.nextLine();
on the second iteration of the menu and sends back
java.util.NoSuchElementException: No line found
Question: I need the program to pause or something similar after showMenu(); to let the user input a menu selection, currently the menu displays and the program crashes instantly
Cheers
public class Menu {
public static char selection;
public static String quitting = "you dun son";
public static String errorMessage = "THAAAAATSS A menu WRRRAAAAAPPP";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
do {
showMenu();
String menu = in.nextLine();
if (menu.length() > 0) {
selection = menu.toLowerCase().charAt(0); // extract the first char of the line read
} else {
selection = '\0';
System.out.println("invalid input:\t" + selection);
System.out.println("Press enter to continue...");
}
switch (selection) {
case 'f':
FuelConsole fuelObject = new FuelConsole();
fuelObject.fuelCalc();
break;
case 'g':
GameConsole gameObject = new GameConsole();
gameObject.gameCalc();
break;
case 'q':
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 'Q' && selection != 'q');
{
System.out.println(quitting);
System.exit(0);
}
}catch (Exception e) {
System.out.println(errorMessage);
}
}
a test method:
public class FuelConsole {
public static String errorMessage = "THAAAAATSS A fuel calc WRRRRAAAAAPPPPPPPPPPPP";
public static Double acceptableCentsPerLitre = 16.00;
Scanner scan = new Scanner(System.in);
public void fuelCalc() {
try {
System.out.println("\nyou selected option 'f' --- here you will enter some information and find average fuel for ONE trip. ");
System.out.println("please enter the amount of fuel in litres:\n ");
float fuel = scan.nextFloat();
System.out.println("please enter the price of fuel in cents (not dollars and cents, only CENTS (lulz)):\n ");
int cent = scan.nextInt();
System.out.println("please enter the number of kilometers travelled on the tank:\n ");
float kilo = scan.nextFloat();
float returnAFC = afc(fuel, kilo);
float returnAC = ac(returnAFC, cent);
System.out.println("average consumption: \t" + returnAFC);
System.out.println("average cost: \t\t" + returnAC);
if (returnAC > acceptableCentsPerLitre) {
System.out.println("Average fuel is above 16c per litre");
} else {
System.out.println("Average fuel is below 16c per litre");
}
} catch (Exception e) {
System.out.println(errorMessage);
e.printStackTrace();
} finally {
scan.close();
}
}
public static float afc(float x, float z) {
float result = x / z;
return result;
}
public static float ac(float x, int y) {
float result = x * y;
return result;
}
}
I think the problem is that you create a new Scanner in the FuelConsole Class.
And you also close it in the finally block.
But when you call close() on scanner it also closes the underlaying InputStream too. (System.in in this case) And because your top-level Scanner uses the same InputStream, it cannot catch any more input from it.
The solution could be if you pass the top level scanner as an argument to other objects:
case 'f':
FuelConsole fuelObject = new FuelConsole();
fuelObject.fuelCalc(in);
break;
case 'g':
GameConsole gameObject = new GameConsole();
gameObject.gameCalc(in);
break;
and
public void fuelCalc(Scanner scan) {
try {
...
and delete the finally block
my instructions on the project were as followed:
Instructions: Use a sentinel value loop. To create a basic Rental Car Calculator
Ask each user for:
Type of vehicle (May use something other than strings, such as: 1 for an economy, 2 for a sedan, etc.)
Days rented
Calculate the (For each customer):
Rental cost,
Taxes,
Total Due.
There are three different rental options with separate rates: Economy # 31.76, sedan # 40.32, SUV # 47.56. [Note: only whole day units to be considered (no hourly rates)].
Sales tax is = to 6% on the TOTAL.
Create summary data with:
Number of customers
Total money collected.
Also, Include IPO, algorithm, and desk check values (design documents).
{WHAT I HAVE GOING AND MY QUESTION(S)}
package tests;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Tester {
public static void main(String []args){
int count=0;
int days;
int cus = 10;
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
boolean F1 = false, F2 = false, F3 = false;
Scanner in=new Scanner(System.in);
while (F3 == false) {
F3 = true;
System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
try {
cus=in.nextInt();
if (cus == 0 || cus == 1) {
F3 = true;
} else {
F3 = false;
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
F3 = false;
System.out.println("Invalid entry");
in.next();
}
}
if(cus == 1) {
while(F1 == false) {
F1 = true;
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
//
try {
CarType = in.nextInt();
if (CarType <= 0 || CarType >= 4) {
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
F1 = false;
} else {
if (CarType == 1) {
F1 = true;
DailyFee=31.76;
} else if(CarType == 2) {
F1 = true;
DailyFee=40.32;
} else if(CarType == 3) {
F1 = true;
DailyFee=47.56;
}
while (F2 == false) {
F2 = true;
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
F2 = false;
} else {
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
F3 = true;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
F2 = false;
in.next();
}
}
}
} catch (InputMismatchException ex) {
F1 = false;
System.out.println("Answer must be a number");
}
}
}
in.close();
System.out.println("Count of customers : " + count);
System.out.printf("Total of the Day : $ %.2f", FullTotal);
}
}
{MY QUESTIONS}
When a letter is entered to the prompt "Press 1 to enter Rental Calculator or else press 0 to quit" it displays, an error prompt then the console asks for input again. Similarly, when a letter is inputted at the prompt "What vehicle would you like to rent?" the console continues to print lines with no stop? I do not know how to fix this?
I want my program to allow multiple calculation inputs to be made. However, after full calculation input (Days * Tax * Car Type) the console post summary data rather than looping?
2a. After the prompt "Please enter the number of days rented. (Example; 3) : " and following user input. How would I get my program to loop back to asking "Press 1 to enter Rental Calculator or else press 0 to quit"? with still making 0 prompt my summary data?
I have just "refactored" your code a bit, removed some obsolete code and placed some other code on other locations.
I've also used more clear naming for variables, and followed the naming conventions.
The problem you had, was that you did not in each catch block had a in.next(); meaning that while iterating, the variable kept using the same variable (which was invalid) so kept looping over the error messages.
Now this code is far from perfect, it can easily be improved still, but this should get you started.
package tests;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Tester {
public static void main(String []args){
int count=0;
int days;
int cus;
int carType;
double dailyFee=0, nonTaxTotal, total,fullTotal=0;
boolean checkRunOrQuit = false, chooseTypeVehicle = false, numberOfDAysChosen = false;
Scanner in=new Scanner(System.in);
while ( !checkRunOrQuit ) {
System.out.print("Press 1 to enter Rental Calculator or else press 0 to quit\n");
System.out.println("Please only enter 1 or 0. Also, please only enter number(s) not letter(s)");
try {
cus=in.nextInt();
switch ( cus ) {
case 0: System.out.println("End of application");
System.exit(0); // This will actually end your application if the user enters 0, no need to verify later on
break;
case 1: checkRunOrQuit = true;
break;
default:
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid entry: ");
in.next();
}
}
while( !chooseTypeVehicle ) { // --> simplified comparison
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
try {
carType = in.nextInt();
chooseTypeVehicle = true;
switch ( carType ) {
case 1: dailyFee = 31.76;
break;
case 2: dailyFee = 40.32;
break;
case 3: dailyFee = 47.56;
break;
default:
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
chooseTypeVehicle = false;
break;
}
} catch (InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next(); // -> you forgot this one.
}
}
while ( !numberOfDAysChosen ) {
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
} else {
nonTaxTotal = (dailyFee * days);
total = (nonTaxTotal * 1.06);
fullTotal+=total;
numberOfDAysChosen = true;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
in.next();
}
}
in.close();
System.out.println("Count of customers : " + count);
System.out.printf("total of the Day : $ %.2f", fullTotal);
}
}
Here you go, i modified it a bit and put the whole thing in a while loop (while (cus != 0)) now it is working perfectly, try this code and do let me know if you have questions
package inter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Inter {
public static void main(String []args){
int count=0;
int days;
int cus = 10; // added
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
boolean F1 = false, F2 = false;
Scanner in=new Scanner(System.in);
while (cus != 0) {
while (true) {
System.out.println("If there are any customer press 1 else press 0");
try {
cus=in.nextInt();
if (cus == 0 || cus == 1) {
break;
} else {
System.out.println("Number must be either 1 or 0");
}
} catch (InputMismatchException ex) {
System.out.println("Invalid entry");
in.next();
}
}
if(cus == 1) {
while(F1 == false) {
F1 = true;
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
try {
CarType = in.nextInt();
if (CarType <= 0 || CarType >= 4) {
System.out.print("Number must be 1-3\n");
System.out.println("Please enter 1 for an economy car");
System.out.println("Enter 2 for a sedan car");
System.out.println("Enter 3 for an SUV");
F1 = false;
} else {
if (CarType == 1) {
F1 = true;
DailyFee=31.76;
} else if(CarType == 2) {
F1 = true;
DailyFee=40.32;
} else if(CarType == 3) {
F1 = true;
DailyFee=47.56;
}
while (F2 == false) {
F2 = true;
try {
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = in.nextInt();
if (days <= 0) {
System.out.println("Number of days must be more than zero");
F2 = false;
} else {
//days = in.nextInt();
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be a number");
F2 = false;
in.next();
}
}
F2 = false;
}
} catch (InputMismatchException ex) {
F1 = false;
System.out.println("Answer must be a number");
in.next();
}
}
F1 = false;
}
}
System.out.println("Count of customers : " + count);
System.out.printf("Total of the Day : $ %.2f", FullTotal);
}
}
I don't know how to say
if money(); < 1000 and house(); is == small print your poor
or
if money(); >=1000 and < 5000 and house(); is == to normal to print your ok, your too rich
package ArrayTest;
import java.util.Scanner;
/**
* Created by quwi on 02/12/2017.
*/`enter code here`
public class Happyness {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// house();
// money();
comparison();
}
private static void house() {
// getting user input and using the switch statement to see the size
// of their house
System.out.println("Please enter the size of your house ");
String cap = scanner.next();
switch (cap) {
case "small":
System.out.println("you have a small house it means your poor");
break;
case "normal":
System.out.println("your house normal, it mean your not poor nor rich");
break;
case "large":
System.out.println("your house is big it means your rich");
break;
default:
System.out.println("please choose between: small, normal or large");
break;
}
}
private static void money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
System.out.println("your poor");
} else if (wage >= 1000 && wage < 5000) {
System.out.println("your not poor, your OK");
} else if (wage > 5000) {
System.out.println("your rich, Give me money");
} else {
System.out.println("please enter a number nothing else");
}
}
private static void comparison() {
System.out.println("please enter a number");
int decision = scanner.nextInt();
switch (decision) {
case 1:
money();
break;
case 2:
house();
break;
case 3:
money();
house();
break;
default:
System.out.println("Please choose 1, 2 or 3");
}
}
}
Use return value from both to compare.
private static String money() {
System.out.println("please enter a number");
int wage = scanner.nextInt();
if (wage < 1000) {
return "poor";
} else if (wage >= 1000 && wage < 5000) {
return "ok";
} else if (wage > 5000) {
return "rich";
} else {
//ask for input again or exit, whatever
}
}
Do same for the house(). Then, compare the return values from both in another method.
I am trying to create a program that asks users for input values for variables in the quadratic equation. I want the code to deal with bad input with the use of exception handling. Bad input would be: non-numeric values where numeric values are excepted. Where i am running into a problem is when a bad value is entered instead of terminating the program i want the code to re request an input. So, in cases where Non-numeric, A=0 or B and C both = 0.
The code below has some errors but I was wondering if someone could help me crack this one! Thanks alot
import java.util.InputMismatchException;
import java.util.Scanner;
//Program that does quadratic equations with exceptions
public class Quadratic{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double a ;
do{
try{
System.out.print("Enter a value for 'a': ");
a =sc.nextDouble();
}
catch (InputMismatchException ex)
{
System.out.println("not a valid character..");
System.out.println("please try again:");
sc.nextDouble(); //prompt user again
}
}while (a==0);
System.out.println("value can not be equal to 0. Please enter another value:\n");
a= sc.nextDouble();
}
}
Your code currently doesn't show you're getting any input for variables B or C but error handling of them should be similar to what can do with input here for 'a':
import java.util.InputMismatchException;
import java.util.Scanner;
//Program that does quadratic equations with exceptions
public class Quadratic{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double a = 0.0 ;
boolean valid_a = false;
while(!valid_a){
try{
System.out.print("Enter a value for 'a': ");
a = sc.nextDouble();
if (a==0){
System.out.println("value can not be equal to 0. Please enter another value:");
}
else{
valid_a = true;
}
}
catch (InputMismatchException ex){
System.out.println(ex);
sc.next();
System.out.println("not a valid character..");
System.out.println("please try again:");
}
}
}
}
Hope this helps!
import java.util.InputMismatchException;
import java.util.Scanner;
//Program that does quadratic equations with exceptions
public class Quadratic{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double a, b, c;
boolean valid_a = false;
a = 0.0;
while(!valid_a){
try{
System.out.print("Please enter value for 'a': ");
a = sc.nextDouble();
if (a == 0){
System.out.println("VALUE CANNOT BE 0, PLEASE TRY AGAIN.");
}
else{
valid_a = true;
}
}
catch (InputMismatchException e){
System.out.println(e);
sc.next();
System.out.println("INVALID INPUT PLEASE TRY AGAIN");
}
}
boolean valid_b = false;
b = 0.0;
while(!valid_b){
System.out.println("Please enter value for 'b': ");
try{
b = sc.nextDouble();
sc.nextLine();
valid_b = true;
}
catch(InputMismatchException e){
System.out.println(e);
valid_b = false;
System.out.println("INVALID INPUT PLEASE TRY AGAIN");
sc.nextLine();
}
}
boolean valid_c = false;
c = 0.0;
while(!valid_c){
System.out.println("Please enter value for 'c': ");
try{
c = sc.nextDouble();
sc.nextLine();
valid_c = true;
}
catch(InputMismatchException e){
System.out.println(e);
valid_c = false;
System.out.println("INVALID INPUT PLEASE TRY AGAIN");
sc.next();
}
}
while(b == 0 && c == 0){
System.out.println("B AND C CANNOT BE BOTH 0. PLEASE RE-ENTER VALID VALUES.");
System.out.println("Value B: ");
b = sc.nextDouble();
System.out.println("Value C: ");
c = sc.nextDouble();
}
System.out.println("Value a:" +a);
System.out.println("Value b:" +b);
System.out.println("Value c:" +c);
double determinate = Math.pow(b,2)- (4 * a * c);
if (determinate >= 0){
double qf1 = ((-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c)))) / (2 * a);
double qf2 = ((-b - Math.sqrt(Math.pow(b, 2) -(4 * a * c))))/ (2 * a);
// qf stands for Quadratic Formula
System.out.printf("Anwser One: %s \n", qf1);
System.out.printf("Anwser Two: %s \n", qf2);
}
else{
System.out.println("DETERMINATE IS NEGATIVE, THEREFORE THERE ARE NO REAL ROOTS.");
}
System.out.println("PROGRAM IS COMPLETE");
return;
}
}``