Quadratic Equation (handle exceptions) for illegal inputs - java

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;
}
}``

Related

How could I print the return numbers instead if alpha

I want to test program that prompts the user to enter a letter grade and displays the quality points by calling the above method in a try-catch block.
import java.util.*;
import javax.lang.model.util.ElementScanner14;
public class Lab17 {
public static int qualityPoint(String alpha) {
if (alpha.equals("A+"))
return 4;
else if (alpha.equals("A"))
return (int) 3.75;
else if (alpha.equals("B+"))
return (int) 3.5;
else if (alpha.equals("B"))
return 3;
else if (alpha.equals("C+"))
return (int) 2.5;
else if (alpha.equals("C"))
return 2;
else if (alpha.equals("D+"))
return (int) 1.5;
else if (alpha.equals("D"))
return 1;
else if (alpha.equals("F"))
return 0;
else
throw new InputMismatchException("Invalid grade");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a letter grade: ");
String alpha = sc.next();
try {
int res = qualityPoint(alpha);
System.out.println("The quality points " + alpha);
} catch (InputMismatchException ex) {
System.out.println("Exception: Enter just a letter grade");
}
}
}
Enter a letter grade:
A
The quality points A
I want the output to be
Enter a letter grade:
A
The quality points A
or
Enter a letter grade:
x
Invalid grade
You can mistake it, use res instead of alpha.
int res = qualityPoint(alpha);
System.out.println("The quality points " + res);

Cant get my integers to add to get correct output

so I am trying to do my homework, this being the question:
Write a program that prompts the user to read two integers and displays their sum. If anything but an integer is passed as input, your program should catch the InputMismatchException that is thrown and prompt the user to input another number by printing "Please enter an integer."
Below is the sample run and what I am supposed to test.
SAMPLE RUN #1: java InputMismatch
Enter an integer: 2.5↵
Please enter an integer↵
Enter an integer: 4.6↵
Please enter an integer↵
Enter an integer: hello!↵
Please enter an integer↵
Enter an integer:7↵
Enter an integer:5.6↵
Please enter an integer↵
Enter an integer:9.4↵
Please enter an integer ↵
Enter an integer:10↵
17↵
When I am testing my code and putting in the integers, it works as it is supposed to, however, I am stuck on getting the integers to add together when both inputs are entered correctly. What am I doing wrong?
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
try adding another condition to your while and putting the numbers in an array.
int[] numbers = new int[2];
and change this in your while loop:
int count = 0;
while (!isValid && count <2) {
try {
System.out.print("Enter an integer: ");
numbers[count] = input.nextInt();
count++;
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
Hope that helped.
Check with this approach:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
numArray[count] = number;
count++;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
int num1 = numArray[0];
int num2 = numArray[1];
System.out.println((num1 + num2));
}
You need to stitch together the logic. As you are taking 2 numbers 2 flags will ensure you got correct input for both variables. Also both flags ensure you are taking input correctly for num1 or num2 when an exception occurs.
If you need to input n arbitrary integers, then you may want to use dynamic collections and add numbers to collection.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean num1Valid = false;
boolean num2Valid = false;
while (num1Valid==false || num2Valid==false) {
try {
if(num1Valid == false) {
System.out.print("Enter an integer for num1: ");
num1 = input.nextInt();
System.out.println("The number entered for num1 is " + num1);
num1Valid = true;
}
if(num2Valid == false) {
System.out.print("Enter an integer for num2: ");
num2 = input.nextInt();
System.out.println("The number entered for num2 is " + num2);
num2Valid = true;
}
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
input.close()
System.out.println((num1 + num2));
}
You need capture the exception, in this case you can using e.getMessage()
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1=0, number=0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
number = input.nextInt();
if(number > 0) {
System.out.println("The number entered is " + number);
}
num1 += number;
System.out.println("are would you like continue the program? Y or
N ");
String condition = input.next();
if(condition.equalsIgnoreCase("Y")) {
isValid = false;
} else {
isValid = true;
}
}
catch (InputMismatchException ex) {
System.out.println(ex.getMessage());
System.out.println("You cannot type words");
isValid = true;
}
}
System.out.println("Result = " + num1);
input.close();
}
}
in another case do you can use the method matches using expression language
saw example below:
if(valor.matches("[0-9]*"))
You can add the two numbers inside the try block
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
num1 = input.nextInt();
System.out.print("Enter an integer: ");
num2 = input.nextInt();
System.out.println("The numbers you entered are " + num1 + ","+num2);
int sum = num1+num2;
System.out.println("The sum Of the numbers you entered is: "+ sum);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer:");
int number = input.nextInt();
numArray[count] = number;
count++;
} catch (InputMismatchException e) {
System.out.println("Please enter an integer.");
input.nextLine();
}
}
System.out.println(numArray[0] + numArray[1]);
}
}

Having an issue with where to call input validity checks

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;
}
}

Java Character Input With Loop?

Guys I want to write a program which find Nominator and Denominator with Exception Handling and calculate their result. I also added a Simple Interface which is Would you like to continue press 'y'. or 'n'. Character is in Lower Case.
I Want that Interface Occur only on two things.When Program Catch the Wrong Input. And When Result Is Calculated.
Problem is when user press 'n' it does not quit.Or When user enter any characters like 'aadswe' Interface does not again appear. I'm Stuck at this Problem.
public class Main {
public static void main(String[] args) {
int numeator;
int denominator;
double result;
Scanner s = new Scanner(System.in);
char m = 'y';
do {
try {
System.out.print("Enter Numenator:");
numeator = s.nextInt();
System.out.print("Enter Denominator:");
denominator = s.nextInt();
result = numeator / denominator;
System.out.println("Answer: " + result);
} catch (InputMismatchException e) {
System.out.println("error=> must enter integer values");
} catch (ArithmeticException e) {
System.out.println("error=> falseairthmtic");
}
System.out.println("Would you continue prees 'y' or quit press 'n'");
m = s.next().charAt(0);
}
while (m == 'y');
}
}
Use following code-
public static void main(String[] args) {
int numeator;
int denominator;
double result;
Scanner s = new Scanner(System.in);
char m = 'y';
do {
try {
System.out.print("Enter Numenator:");
numeator = s.nextInt();
System.out.print("Enter Denominator:");
denominator = s.nextInt();
result = numeator / denominator;
System.out.println("Answer: " + result);
} catch (InputMismatchException e) {
System.out.println("error=> must enter integer values");
} catch (ArithmeticException e) {
System.out.println("error=> falseairthmtic");
}
System.out.println("Would you continue prees 'y' or quit press 'n'");
m = s.next().charAt(0);
while(m!='y'&& m!='n'){
System.out.println("you can press only 'y'or'n' "+ m+ " is not allowed!!") ;
m = s.next().charAt(0);
}
}
while (m == 'y');
System.out.println("Has been quit");
}

Loop hole in loop's logic

I am trying a program on exception handling to calculate height in centimeters.
import java.util.*;
class Ex{
private static double height(int feet, int inches) throws Exception{
if(feet < 0 || inches < 0)
throw new Exception("Please enter positive values only.");
return (feet * 30.48) + (inches * 2.54);
}
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
boolean continueLoop = true;
do{
try
{
System.out.println("Enter height in feet:");
int feet=scanner.nextInt();
System.out.println("and in inches:");
int inches = scanner.nextInt();
double result = height(feet,inches);
System.out.println("Result:"+result+" cm");
continueLoop = false;
}
catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
}
catch(Exception e){
System.out.println(e.getMessage());
}
}while(continueLoop);
}
}
When an InputMismatchException occurs, the program enters into an infinite loop. What is the fault in my logic here? What change(s) should I do?
You should add scanner.nextLine() to your catch blocks, in order to consume the rest of the current line, so that nextInt can attempt to read new input from the next line.
do{
try
{
System.out.println("Enter height in feet:");
int feet=scanner.nextInt();
System.out.println("and in inches:");
int inches = scanner.nextInt();
double result = height(feet,inches);
System.out.println("Result:"+result+" cm");
continueLoop = false;
}
catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
scanner.nextLine();
}
catch(Exception e){
System.out.println(e.getMessage());
scanner.nextLine();
}
}while(continueLoop);

Categories

Resources