Loop hole in loop's logic - java

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

Related

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

Quadratic Equation (handle exceptions) for illegal inputs

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

Exception not being executed

Im constructing a program in which the user inputs a height between 3 and 10 and a triforce from zelda is printed in java. At the current moment, whenever the user inputs numbers outside that range an exception is thrown, however I want the program to throw an exception whenever any string is inputted. Im not sure how to utilise the InputMismatchException. This is my code so far:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int height;
try {
System.out.print("Enter height: ");
height = keyboard.nextInt();
}
catch (InputMismatchException e) {
System.out.println("");
System.out.println("Invalid height.");
}
if (height < 3 || height > 10) {
System.out.println("Invalid height.");
System.exit(0);
}
try {
System.out.print("Enter height: ");
height = keyboard.nextInt();
if (height < 3 || height > 10) {
System.out.println("Invalid height.");
System.exit(0);
}
// print triforce from zelda
// ...
} catch (InputMismatchException e) {
System.out.println("please input a int");
}

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

Endless loop with try and catch JAVA

so what I am trying to do is have the user input a valid coordinate in a matrix, that is an INT which is greater than -1,
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
while (((coordinates[1]<0)||(coordinates[1]>C)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
the problem is that it loops endlessly after entering a not valid input
int R is the size of the row
int C is the size of the collumn
Your problem is that you're not handling the error you're catching.
If you'll provide wrong format of number for the nextInt() method, then the InputMismatchException will be thrown. Then because the catch does nothing, the loop will continue (start from begining) and the scanner will read the same incorrect value, and so on...
So instead of this:
catch (InputMismatchException e) {
}
Try this:
catch (InputMismatchException e) {
System.out.println("Wrong number entered.");
scanner.nextLine();
}
This way you'll force scanner to move past the last incorrect input.
EDIT:
You're loop is also broken because you do break after reading the input. In that case if you'll put the negative number you'll break as well and won't check the loop condition. Remove the break statement and it will work as expected:
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
EDIT2:
public static void main(final String args[])
{
int maxRowsNumber = 10;
int maxColsNumber = 10;
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>maxRowsNumber)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
while (((coordinates[1]<0)||(coordinates[1]>maxColsNumber)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
System.out.println("Inserted RowsNumber: " + coordinates[0]);
System.out.println("Inserted RowsNumber: " + coordinates[1]);
}
Output:
Please enter a valid row number: 11
Please enter a valid row number: 22
Please enter a valid row number: 10
Please enter a valid col number: 11
Please enter a valid col number: 2
Inserted RowsNumber: 10
Inserted RowsNumber: 2
If by "not valid input" you mean "not any kind of integer", then your scanner will fail each time it tries to read another integer, so you'll hit your catch, and do nothing to stop the loop. Maybe you intended to set check to false in such circumstances? Or maybe you meant to put the break in each catch?
Using a break when a valid integer is read isn't right, because it might be a negative integer, which your loop guard says you don't want.
This is basically the same as what your doing, I just tried to improve it a little bit by removing hardcoded values, made variables more descriptive, and included input validations.
final int ROW = 0;
final int COL = 1;
int coordinates[] = new int[2];
coordinates[ROW] = -1;
coordinates[COL] = -1;
boolean isInputValid = true;
Scanner scanner = new Scanner(System.in);
do {
try {
System.out.print("Please enter a valid row number:\t");
coordinates[ROW] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false; //if the input is not int
}
} while (!isInputValid && (coordinates[ROW] < 0) //do this until the input is an int
|| (coordinates[ROW] > R)); //and it's also not less than 0 or greater than R
//same logic applies here
do {
try {
System.out.print("Please enter a valid col number:\t");
coordinates[COL] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false;
}
} while (!isInputValid && (coordinates[COL] < 0)
|| (coordinates[COL] > C));
Hope this helps.

Categories

Resources