Issues with InputMismatchException not being used properly - java

Im trying to create a code where I read a double and print out its square, but I also want it to know when the user enters a negative or non double constant and make them enter a new number. Im having trouble with the InputMismatchException. My code does not work properly, it compiles but the compiler just runs forever. Any suggestions would be helpful.
import java.util.*;
class constants
{
public static void main(String[] args)
{
double constant = getConstant();
System.out.println("Square of " + constant + " = " + constant*constant);
}
//-------------------------------------------------------------------------------
public static double getConstant()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter non-negative double constant");
double constant = kb.nextDouble();
try {
double selection = kb.nextDouble();
}
catch (InputMismatchException e) // where there is error.
{
System.out.println("Not a double constant. Re-enter");
}
return constant;
}
}

Here is how it can be done, the exception you need to catch is NumberFormatException. One thing though, negative numbers can still have squares, they just can't have square roots.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
try {
double temp = kb.nextDouble();
//If the input is not a double, catch the number format exception
} catch (NumberFormatException e) {
e.printStackTrace();
}
//If the number is in proper format, (can be negative) print its square.
System.out.println("Square of " + temp+ " = " + temp*temp);
}
For some reason if you don't want to print squares of negative numbers, just check that condition before printing the result.

I understand that you are looking for the user to input such values as 15.65, 145.95, etc, but that -5.85 (negative) and 11 (integer value) should be rejected. The fact is, in java any integer is also a double
Example:
double x = 100; // is correct
double y = -15.85 // is correct
Therefore they will not generate an input mismatch exception. For that you have to check explicitely that these conditions are met and you will also have to explicitely throw the InputMismatchException.
It is also better to define your scanner once, for example as a global static variable (otherwise you may face issues if you use call getConstant() in a loop for example)
You don't need to define the selection double value. Here is an illustration that works
import java.util.InputMismatchException;
import java.util.Scanner;
class Constants
{
private static Scanner kb = new Scanner(System.in);
public static void main(String[] args)
{
double constant = getConstant();
if (constant >= 0) {
System.out.println("Square of " + constant + " = " + constant*constant);
}
}
//-------------------------------------------------------------------------------
public static double getConstant()
{
System.out.println("Enter non-negative double constant");
double constant=-1.0D;
try {
constant = kb.nextDouble();
// you don't want the negative value neither the integer value
// so you reject them by throwing the InputMismatchException
if (constant <0 || Math.floor(constant) == constant * 1.0D) {
constant = -1.0D;
throw new InputMismatchException("Not a double constant. Re-enter");
}
}
catch (InputMismatchException e) // where there is error.
{
System.out.println("Not a double constant. Re-enter");
}
return constant;
}
}

Related

Returning to the specific place in program after handling the exception

Good morning.
I suppose it's a very simple question for you guys...
In below code, exception NumberFormatException, can be thrown in to places, when we provide value for "a" and "b" variables. Catch block handles exceptions by starting the method again, no matter if the exception was trigged by wrong value of "a" or "b".
I would like to change the code in a way that if the exception occurs while providing value for varaible "b", the method start not from the very beginning, but from the place where I'm suppose to provide value for "b" (in other words I don't want the user to go again from the start and provide value for "a" variable
Suppose I could insert two more methods handling the code where I provide the values for "a" and "b" ... but is there any other way to get the same functionality without implementing new methods ?
import java.io.*;
public class Rozdzial1{
public static void Zadanie11()
throws IOException
{
try {
Double a, b, area;
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader read = new BufferedReader(input);
System.out.println("The program calcultes area of rectangle");
System.out.println("Provide length of first edge: ");
a = Double.parseDouble(read.readLine());
System.out.println("Length of the first edge is: " + a);
System.out.println("Provide length of second edge: ");
b = Double.parseDouble(read.readLine());
System.out.println("Length of the second edge is: " + b);
area = a*b;
System.out.println("Area of provided rectangle is: " + area);
}
catch (NumberFormatException exception) {
System.out.println("Provided vale should be a number, please try again\n");
Rozdzial1.Zadanie11();
}
}
public static void main(String[] args)
throws IOException
{
Rozdzial1.Zadanie11();
}
}
Reading values until valid value is entered should be extracted into a separate method, which should be called for a and b variables separately.
public static void main(String[] args) {
Task1();
}
public static void Task1() {
Scanner scan = new Scanner(System.in);
System.out.println("The program calculates area of rectangle");
double a = readValue(scan, "first edge");
double b = readValue(scan, "second edge");
System.out.println("Area of provided rectangle is: " + (a * b));
}
private static double readValue(Scanner scan, String name) {
try {
System.out.println("Provide length of " + name + ": ");
return Double.parseDouble(scan.nextLine()); // exit from recursion with valid value
} catch (NumberFormatException numex) {
System.out.println("Provided value should be a number, please try again");
return readValue(scan, name); // recursive call for invalid value
}
}
Another option (without creating a separate method) could be to use nested loops to read inputs until valid value is provided:
public static void Task2() {
Scanner scan = new Scanner(System.in);
System.out.println("The program calculates area of rectangle");
String[] names = {"first edge", "second edge"};
double[] arr = new double[2];
for (int i = 0; i < arr.length; i++) {
try {
System.out.println("Provide length of " + names[i] + ": ");
arr[i] = Double.parseDouble(scan.nextLine());
} catch (NumberFormatException numex) {
System.out.println("Provided value should be a number, please try again");
i--; // repeat the input
}
}
System.out.println("Area of provided rectangle is: " + (arr[0] * arr[1]));
}

Java: Using Try/Catch Exception to check if user input is Double

I am writing a simple program that allows a user to enter two separate doubles for a foot and inch measurement. The program is intended to take these values and convert them to centimeters and output them. Additionally I am to include two exceptions: one to make sure the numeric values are positive and not negative (this one I have completed) and another to make sure the input entered is a double value and not a string value (this one I am having a hard time with). So if a user enters an input... for example 'Bill' instead of a number, it is to display an error message and ask the user to re-enter the input values again.
It seems like perhaps I would be best off gathering the user input as a string (rather than doubles as I currently am), which I convert to doubles and return them as doubles to their corresponding methods: getFootValue() and getInchValue() -- but I am not too sure.
How should I go about implementing this by way of a custom exception? I cannot simply utilize the InputMismatchException, I need to make my own titled NonDigitNumberException().
Here is what I have so far...
import java.util.Scanner;
public class Converter
{
private double feet;
private double inches;
public Converter(double feet, double inches)
{
this.feet = feet;
this.inches = inches;
}
public double getFootValue()
{
return feet;
}
public double getInchValue()
{
return inches;
}
public double convertToCentimeters()
{
double inchTotal;
inchTotal = (getFootValue() * 12) + getInchValue();
return inchTotal * 2.54;
}
public String toString()
{
return ("Your result is: " + convertToCentimeters());
}
}
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestConverter
{
public static void main(String[] args)
{
/* Create new scanner for user input */
Scanner keyboard = new Scanner(System.in);
do
{
try
{
/* Get the feet value */
System.out.print("Enter the foot value: ");
double feet = keyboard.nextDouble();
if (feet < 0) throw new NegativeNumberException();
/* Get the inches value */
System.out.print("Enter the inch value: ");
double inches = keyboard.nextDouble();
if (inches < 0) throw new NegativeNumberException();
else
{
Converter conversion = new Converter(feet, inches);
/* Print the converted result */
System.out.println(conversion);
break;
}
} catch(InputMismatchException ignore){}
catch(NegativeNumberException error)
{
System.out.println("A negative-numeric value was entered, please enter only positive-numeric values...");
}
}while(true);
/* Close the keyboard */
keyboard.close();
}
}
class NegativeNumberException extends Exception
{
public NegativeNumberException()
{
super();
}
public NegativeNumberException(String errorMessage)
{
super(errorMessage);
}
}
Thanks for any help!
You're over complicating things. You can simply use the Scanner.hasNextDouble() method.
Example:
Assuming this code is inside your main method.
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter value");
double myValue = 0;
if(scanner.hasNextDouble()){
myValue = scanner.nextDouble();
}else{
System.out.println("Wrong value entered");
}
}
}
you can then go on and use myValue with your Converter class.
UPDATE
It seems that you must create your own exception class according to what you have told me within the comments. So, I have decided to implement that for you and hopefully, you can be able to carry on from here.
Custom Exception Class
public class NonDigitNumberException extends InputMismatchException {
public NonDigitNumberException(String message){ // you can pass in your own message
super(message);
}
public NonDigitNumberException(){ // or use the default message
super("input is not a digit");
}
}
Negative Number Exception Class
public class NegativeNumberException extends IllegalArgumentException {
public NegativeNumberException(String message){ // you can pass in your own message
super(message);
}
public NegativeNumberException(){ // or use the default message
super("negative number is not valid");
}
}
Validator Method
public static double inputValidator(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter a value"); // prompt user for input
String getData = scanner.next(); // get input
if(getData.length() >= 1){
if(!Character.isDigit(getData.charAt(0)) && getData.charAt(0) != '-') throw new NonDigitNumberException();
}
for (int i = 1; i < getData.length(); i++) {
if(!Character.isDigit(getData.charAt(i))) throw new NonDigitNumberException();
}
return Double.parseDouble(getData); // at this point the input data is correct
}
Negative Number Validator
public static boolean isNegative(double value){
if(value < 0) throw new NegativeNumberException();
return false;
}
Main method
public static void main(String[] args) {
try {
double myValue = inputValidator();
System.out.println(isNegative(myValue)); // check if number is negative
}catch (NegativeNumberException e){
e.printStackTrace();
}
catch (NonDigitNumberException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
Do you really need a custom exception? Because keyboard.nextDouble() already throws InputMismatchException if the input is not a double.
Instead of ignoring the exception, you should show an error message (saying the user didn't type a number).
I guess, you are mixing things up:
You have to validate the input of the user first, if it is a double. If it is not, then you are getting an InputMismatchException.
Then you have to validate the input, if it is valid for your converter (is it positive?). Here you can throw your custom exception.
And then you call your Converter, which might also throw your custom exception.
So my solution would be:
import java.util.Scanner;
import java.util.InputMismatchException;
public class TestConverter {
public static void main(String[] args) {
/* Create new scanner for user input */
Scanner keyboard = new Scanner(System.in);
do {
double feet = -1, inches = -1;
Exception exception;
do {
exception = null;
/* Get the feet value */
System.out.print("Enter the foot value (positive-numeric): ");
try {
feet = keyboard.nextDouble();
} catch (InputMismatchException e) {
keyboard.next();
exception = e;
}
} while (exception != null);
do {
exception = null;
/* Get the inches value */
System.out.print("Enter the inch value (positive-numeric): ");
try {
inches = keyboard.nextDouble();
} catch (InputMismatchException e) {
keyboard.next();
exception = e;
}
} while (exception != null);
try {
if (feet < 0) throw new NegativeNumberException();
if (inches < 0) throw new NegativeNumberException();
Converter conversion = new Converter(feet, inches);
/* Print the converted result */
System.out.println(conversion);
break;
}
catch(NegativeNumberException error) {
System.out.println("A negative-numeric value was entered, please enter only positive-numeric values...");
}
} while (true);
/* Close the keyboard */
keyboard.close();
}
}
Output
Enter the foot value (positive-numeric): test
Enter the foot value (positive-numeric): 1234
Enter the inch value (positive-numeric): test
Enter the inch value (positive-numeric): 1234
Your result is: 40746.68

Type mismatch:could not convert from int to boolean

In the if statement, within the argument I get an error saying "type mismatch, could not convert from int to boolean". Please provide a solution.
public static void main(String[] args) {
Scanner sathya1 = new Scanner(System.in);
System.out.println("Enter the numbers");
int x = (sathya1.nextInt());
int y = (sathya1.nextInt());
int addition = x+y;
int subtraction = x-y;
int multiplication = x*y;
float division = x/y;
if(sathya1.nextInt(addition){
System.out.println("The number is " +addition);
elseif(sathya1.nextInt(subtraction)){
System.out.println("The number is " +subtraction);
elseif(sathya1.nextInt(multiplication)){
System.out.println("The number is " +multiplication);
elseif(sathya.1nextInt(division)){
System.out.println("The number is " +division);
}
}
}
}
}
}
The line
if(sathya1.nextInt(addition){
makes no sense. It's like saying "if 12". The same goes for the other lines. In addition, you're missing a closing ), among lots of other problems.
Maybe you mean:
import java.util.Scanner;
public class BasicArithmetic
{
public static void main(String[] args)
{
//create a scanner for keyboard input
Scanner sathya1 = new Scanner(System.in);
//ask user for the operation to be used
System.out.print("Please enter the corresponding number to be used \n(1)for Addition,(2)for Subtraction,(3)for Multiplication,(4)for Division:");
int enteredNumber = sathya1.nextInt();
//get the two numbers to be used
System.out.println("Enter the numbers");
float x = sathya1.nextFloat();
float y = sathya1.nextFloat();
//arithmetic operations of the two numbers
float addition = x+y;
float subtraction = x-y;
float multiplication =x*y;
float division = x/y;
//if..else statement
if(enteredNumber==1)
{
System.out.println("The sum of the two number is "+addition);
}
else if(enteredNumber==2)
{
System.out.println("The subtraction of the two number is "+subtraction);
}
else if(enteredNumber==3)
{
System.out.println("The product of the two number is "+multiplication);
}
else if(enteredNumber==4)
{
System.out.println("The quotient of the two number is "+division);
}
else
{
System.out.println("Please enter the correct corresponding number");
}
}
}

In Java, how can I use a variable initialized inside a try/catch block elsewhere in the program?

I have a basic quadratic formula program, but I've modified the beginning to end the program if any value other than a double is entered. However, because I've done this, I can't seem to be able to use the value inputted anywhere else in the program. Here are the first few lines:
import java.util.Scanner;
public class QuadraticFormula
{
public static void main(String[] args)
{
double a, b, c;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
The rest of the program asks for the values of b and c, and then carries out the quadratic equation, retuning the roots of whatever equation was entered. However, because the value of a is defined inside the try section, the compiler tells me that a hasn't been initialized. How do I fix this?
EDIT: I do want to use the data inputted by the user in the program (stored as doubleString)––but a number. My immediate problem is the compiler error, but is there any way to use the information inputted even though it's inside the try block? Because when I tried to equate double a to double doubleString outside the block it said doubleString didn't exist.
Like #Elliot Frisch said, you can just initialize a to a value (0) and take care that you don't get any wrong values due to failed parsing.
In your case this would probably mean to return/exit the program with the error message.
This is actually a common pattern.
import java.util.Scanner;
public class QuadraticFormula
{
public static void main(String[] args)
{
double a = 0, b, c;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
return;
}
//do work with a
Just initialize a when you declare it :
public static void main(String[] args)
{
double a = 0.0;
double b, c;
Scanner reads = new Scanner(System.in);
The other thing you can do is declare a as a "Class Property" :
public class QuadraticFormula
{
protected static double a = 0.0;
public static void main(String[] args)
{
double b, c;
Scanner reads = new Scanner(System.in);
try {
String doubleString = reads.nextLine();
QuadraticFormula.a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
Please note how the Class property (a) MUST be accessed using a static reference within main() as main() is static, which breaks the Java rule of using getter/setter to access Class properties. One thing I would recommend you should begin to learn how to package Class functionality outside of main()...outside of static references...
import java.util.Scanner;
public class QuadraticFormula {
protected double a = 0.0;
public static void main ( String[] args ) {
QuadraticFormula lnewItem = new QuadraticFormula();
try {
lnewItem.doSomething();
} catch ( Exception e ) {
e.printStackTrace();
}
}
public void doSomething () throws Exception {
double b, c;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
setA ( Double.parseDouble(doubleString) );
System.out.println("setA() - [" + getA() + "]");
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
}
public double getA () {
return a;
}
public void setA ( double a ) {
this.a = a;
}
}
Please note in the last section of code, all the static references are removed other than main(). New getter/setter methods are in place for the Class property a, thus enforcing Java's data encapsulation.
There are two fixes for this, one is to simply return from your main method when an exception is throw like so:
double a;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
return;
}
The other option stated by others is giving 'a' an initial value. I would suggest initializing it as NaN (Not a Number) and then checking it has been properly initialized before using it like so:
double a = Double.NaN;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
if(Double.isNaN(a)){
System.out.println("Variable 'a' is invalid, please enter a valid number.");
}
else {
double result = 2 * a;
}
instead of this line:
double a, b, c;
just replace it with this:
double a=0, b, c;

Why do I get a DivideByZeroException in my Java code?

import java.io.IOException;
import java.util.*;
public class calling {
public static String s;
public static String t;
public static int y;
public static int x;
public static int num1() {
int x;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number called x: ");
x=scanner.nextInt();
return x;
}
public static int num2() {
int y;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number called y: ");
y=scanner.nextInt();
return y;
}
public static void calculation() {
Scanner input = new Scanner(System.in);
System.out.println("What process would you like to do? *, /, + or - ?");
s=input.next();
if (s.equals("*")) {
System.out.println("\nThe product of these numbers is:" + (x*y));}
else
if (s.equals("+")) {
System.out.println("\nThe sum of these numbers is: " + (x+y));}
System.out.println("\nDo you want x or y to be the dividor/subtractor?: ");
t=input.next();
if (t.equals("y") || t.equals("Y") ) {
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (x/y));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + (x-y));}}
else
if (t.equals("x") || t.equals("X")){
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (y/x));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + ((y-x)));}}
}
public static void main (String [] args) throws IOException {
num1();
num2();
calculation();
}
}
i keep getting this error in what should be my final result which is simply the result of the calculations being performed
this is the error:" Exception in thread "main" java.lang.ArithmeticException: / by zero
at calling.calculation(calling.java:44)
at calling.main(calling.java:64)"
Since this is likely homework, I'll give you a hint to point you in the right direction.
When you run your program, you execute num1 and num2 to collect the values of x and y from the user. Within num2, y is declared as a local variable. What happens to that variable when num2 returns? And what does that imply for the class field (variable) y declared on line 7?
This is also a good time to learn how to use a debugger. Put a breakpoint on line 44, and see what the values of x and y are.
You need to make sure that the:
int x;
int y;
are the ones you want. Integer's default to zero when static.

Categories

Resources