can InputMismatchException work for java GUI? - java

In my code, I have 2 exception handling which are InputMismatchException and Exception. The problem I facing right now is the exception handling of InputMismatchException doesn't work and it only works for Exception.
output picture
below is my source code
#Override
public void actionPerformed(ActionEvent e) {
try {
DecimalFormat df = new DecimalFormat("0.0");
double cm = Double.parseDouble(tf1.getText());
double kg = Double.parseDouble(tf2.getText());
double BMI=0;
double m = cm/100;
if(e.getSource() == btCalc) {
BMI = kg / (m * m);
}
tfBMI.setText(String.valueOf(df.format(BMI)));
}
catch(InputMismatchException e1) {
JOptionPane.showMessageDialog(this,"You must enter a number. Please try again.");
}
catch(Exception e2) {
JOptionPane.showMessageDialog(this,"Please Enter your Height and Weight");
}
}
}

Double.parseDouble throws a NumberFormatException, not an InputMismatchException. Change your catch clause accordingly and you should be OK.

Related

all the Numberformat exception below the one which recently got caught are executed on their own

My programs gets two students name and three subject marks and calculate average of the student.In the middle i got to catch numberFormatexception if mark is other than integer and other two user defined exception.
whenever the numberFormatexception is caught,the other numberformatecxceptions below are caught on their own.
import java.util.*;
class ude1 extends Exception
{
public ude1()
{
System.out.println("User defind exception 1 thrown");
}
public String toString()
{
return "NegativeValueException";
}
}
class ude2 extends Exception
{
public ude2()
{
System.out.println("User defind exception 2 thrown");
}
public String toString()
{
return "ValueOutofBouundException";
}
}
class excep6
{
/* String stud_name;
int mark1,mark2,mark3;
excep6(String name,int a,int b,int c)
{
stud_name=name;
mark1=a;
mark2=b;
mark3=c;
}
public void calculator()
{
float avg=0;
avg=(mark1+mark2+mark3)/3;
System.out.println("The average of "+stud_name+" is "+avg);
} */
public static void main(String []args)
{
Scanner in = new Scanner(System.in);
int a=0,b=0,c=0,l=2;
String std="";
while(l>0)
{
try{
System.out.println("enter student name");
std=in.next();
System.out.println("enter mark1");
if(in.hasNextInt())
a=in.nextInt();
else
throw new NumberFormatException();
if(a<0)
{
throw new ude1();
}
if(a>100)
{
throw new ude2();
}
}
catch(ude1 u1)
{
System.out.println(u1.toString());a=0;
}
catch(ude2 u2)
{
System.out.println(u2.toString());a=0;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormat Exception");a=0;
}
System.out.println("enter mark2");
try{
if(in.hasNextInt())
b=in.nextInt();
else
throw new NumberFormatException();
if(b<0)
{
throw new ude1();
}
if(b>100)
{
throw new ude2();
}
}
catch(ude1 u1)
{
System.out.println(u1.toString());b=0;
}
catch(ude2 u2)
{
System.out.println(u2.toString());b=0;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException Exception");b=0;
}
System.out.println("enter mark3");
try{
if(in.hasNextInt())
c=in.nextInt();
else
throw new NumberFormatException();
if(c<0)
{
throw new ude1();
}
if(c>100)
{
throw new ude2();
}
}
catch(ude1 u1)
{
System.out.println(u1.toString());c=0;
}
catch(ude2 u2)
{
System.out.println(u2.toString());c=0;
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException Exception");c=0;
}
System.out.println("The average of student "+std+" is "+(a+b+c)/3);
l--;
}
}
}
I expect
enter the name
sat
enter mark1
i
NumberFormat exception
enter mark2
34
enter mark3
56
the avg is 30
rather than
enter the name
sat
enter mark1
i
NumberFormat exception
enter mark2
NumberFormat exception
enter mark3
NumberFormat exception
enter the name
_
If you call hasNextInt() and it returns false, then call it again, it is guaranteed to return false again.
The hasNextInt() does NOT skip the token that is not an integer. It leaves in in the scanner so that you can attempt to read it as something else.
In most cases, the correct way to recover from unexpected input (e.g. a non-integer when an integer is expected) is to call nextLine() and discard the result. A nextLine() call will consume all characters up to and including the next end-of-line.
You should also take note of the comments about:
following style conventions in class names, and
inappropriate use of custom exceptions.

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

Issues with InputMismatchException not being used properly

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

Need a way to ensure user enters the correct amount, as well as ensuring the user doesn't enter a string [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
The code here worked until I needed to ensure the user didn't cause an exception by entering a string instead of an integer or double. I basically need to make sure the user enters enough to be greater than or equal to the price, so that the program can return the correct amount of change.
public static double findChange()
{
System.out.println("\nPlease insert: " + price + " (enter payment amount)");
while (payment < price)
{
try {
payment = kb.nextDouble();
//takes input until user has entered the needed amount
} catch (Exception e)
{
System.out.println("Error: Please enter valid currency");
}
price = price - payment;
price = (price * 100) / 100;
System.out.println("Please insert:" + price);
if (payment <= price)
stringError = false;
}
}
change = payment - price;
change = Math.round(change * 100);
change = change / 100;
System.out.println("\nChange Given: $" + change);
//determines amount of change to give user and formats to cents
return change;
}
Change
catch (Exception e)
{
System.out.println("Error: Please enter valid currency");
}
to
catch (Exception e)
{
System.out.println("Error: Please enter valid currency");
continue;
}
This way, if the user inputs a non double value, the error message will be shown and he will be asked to re-enter a value (The continue; instruction skips the current iteration & passes on to the next one).
try {
payment = kb.nextDouble();
//takes input until user has entered the needed amount
} catch (Exception e)
{
System.out.println("Error: Please enter valid currency");
}
price = price - payment;
When an exception occurs, this will cause troubles, since payment has no value (or not the right one).
put your catch statement later in the while block
Try the following:
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
findChanges();
}
private static double findChanges()
{
string xPrice;
string xPayment;
double price = 0d;
double payment = 0d;
double change = 0d;
Console.WriteLine("Please insert price and payment amout");
Console.WriteLine("Price ?");
xPrice = Console.ReadLine();
bool PriceIsNumber = double.TryParse(xPrice, out price);
Console.WriteLine("Payment ?");
xPayment = Console.ReadLine();
bool PaymentIsNumber = double.TryParse(xPayment, out payment);
if (PriceIsNumber == true && PaymentIsNumber == true)
{
if (payment > price)
{
try
{
// price = price - payment;
// price = (price * 100) / 100;
change = payment - price;
// change = Math.Round(change * 100);
// change = change / 100;
Console.WriteLine("Change = " + change.ToString());
}
catch (Exception e)
{
// supress or process e
}
}
}
else
{
Console.WriteLine("Please enter valid currency");
}
Console.Read();
return change;
}
}
}

Try/catch in Java

Could someone please give me a hint why this try and catch is not working?
It throws a scanner exception instead of printing the message I expect.
import java.util.*;
import java.io.*;
import java.math.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
Boolean test = true;
while (test == true) {
try {
double x, y;
String operator;
Scanner scan = new Scanner(System.in);
Scanner scan_2 = new Scanner(System.in);
Scanner ScanOperator = new Scanner(System.in);
System.out.println(" Enter a double value: ");
x = scan.nextDouble();
System.out.println(" Enter another double value: ");
y = scan_2.nextDouble();
System.out.println(" Enter a operator for the operation you want to execute, or X if you want to quit: ");
operator = ScanOperator.nextLine();
if (operator.equals("x") || operator.equals("X")) {
test = false;
System.out.println("No calculation was made!!!");
}
System.out.println(Calculation(operator, x, y));
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
}
}
public static double Calculation(String operator, double x, double y) {
double result = 0;
double myAdd = 0;
double mySub = 0;
double myMult = 0;
double myDiv = 0;
double myPower = 0;
double myMod = 0;
if (operator.equals("+")) {
myAdd = x + y;
result = myAdd;
} else if (operator.equals("-")) {
mySub = x - y;
result = mySub;
} else if (operator.equals("*")) {
myMult = x * y;
result = myMult;
} else if (operator.equals("/")) {
myDiv = x / y;
result = myDiv;
} else if (operator.equals("^")) {
myPower = Math.pow(x, y);
result = myPower;
} else if (operator.equals("%")) {
myMod = x % y;
result = myMod;
} else {
}
return result;
}
}
Simple, the program throws ScannerException, but your try catch can only catch NumberFormatException, you need to add another catch clause in order to catch ScannerException, or catch only the generic Exception.
for example, when you say:
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
that is only specifying how to catch NumberFormatException.
In order to catch all exceptions, you would need to make it:
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}catch (Exception e){
JOptionPane.showMessageDialog(null,"Generic exception caught");
}
In this case, the second catch would get everything that was not caught in the first catch because all exceptions extend the Exception class, you can catch all derived classes with that statement.
However, since catching Exception by itself is frowned upon, you could also do:
} catch (NumberFormatException, ScannerException e) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
To catch both exceptions in the same block.
You're attempting to catch a NumberFormatException. You need to add a catch statement for a ScannerException, as it is different from a NumberFormatException.
You need to catch a ScannerException or some like this.
At this code you are only catching the NumberFormatException .
Try some like this:
try {
...
} catch (NumberFormatException, ScannerException exception) {
JOptionPane.showMessageDialog(null,"Input must be a number.");
}
You're catching the wrong exception.
Your code will not throw a NumberFormatException. You should catch an InputMismatchException instead.
Looking at nextDouble, in Scanner, it seems that the Scanner code handles the NumberFormatException for you and then throws a different type of exception:
from java.util.Scanner:
public double nextDouble() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Double)) {
double val = ((Double)typeCache).doubleValue();
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
// Search for next float
try {
return Double.parseDouble(processFloatToken(next(floatPattern())));
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
When you hit a problem like this, I recommend that you look through the Java source as a first stop. It is a great resource.
Also note that there is no ScannerException in the JDK.
Just catch InputMismatchException instead of NumberFormatException and everything works fine.
Why not just do:
String input = scan.nextLine();
if(!input.matches("\\d+")) { // regex for 1 or more digits
System.err.println("Input must be at least 1 digit!");
continue; // goes back to the top of the loop
}
double dbl = Double.valueOf(input);
FYI, the actual regex for double precision would be [digit][.][digit] with the [.][digit] being optional.

Categories

Resources