7 Replies - 195 Views - Last Post: 02 March 2012 - 04:25 PM Rate Topic: -----

#1 Dorito_125  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 88
  • Joined: 13-December 08

Error checking, or is it?

Posted 02 March 2012 - 09:14 AM

One thing that kind of bothers me is that we supposedly do error checking in school. You can make your do while loop and scanner and make it look for an int. That's fine and you can check to make sure that the correct int was entered but what happens if you enter a double or a char. The little java gremlins in the JRE start running around like chickens with their heads cut off your program locks up and so much for error checking. Wasn't that supposed to prevent users from making a mistake? Well they just crashed the whole thing! For this, I introduce SUPREME ERROR CHECKING!!!

Critiques? Criticisms?

/**
 * A method that prompts for a specified input and checks to see if a input is valid 
 *  it will contine to ask until the correct input has been entered. I have not figured out how to crash it yet.
 *  
 *  @author Andrew Hood
 *  @version 3/02/2012
 *  
 */import java.util.*;
import java.io.*;
public class errorCheck
{
    static int getValueExpectInt()
    {
        String _temp = "";
        boolean correctInput;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        do
        {
            try 
            {
                _temp = br.readLine(); 
                correctInput = Integer.valueOf(_temp).getClass().getName().equals("java.lang.Integer");
            }
            catch(Exception ex)
            {
                System.out.print("That's not an integer. Try again: ");
                correctInput = false;
            
            }
        } while(correctInput == false);
        return Integer.valueOf(_temp);
    }
    
    static double getValueExpectDouble()
    {
        String _temp = "";
        boolean correctInput;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        do
        {
            try 
            {
                _temp = br.readLine(); 
                correctInput = Double.valueOf(_temp).getClass().getName().equals("java.lang.Double");
            }
            catch(Exception ex)
            {
                System.out.print("That's not a Double. Try again: ");
                correctInput = false;
            
            }
        } while(correctInput == false);
        return Double.valueOf(_temp);
    }
    
    public static void main(String[] args)
    {
        int myInt;
        double myDouble;
        System.out.print("Please enter an integer: ");
        myInt = getValueExpectInt();
        System.out.print("Pleas enter a double: ");
        myDouble = getValueExpectDouble();
        
        System.out.println("Your int: " + myInt + " Your double: " + myDouble);
        
        
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Error checking, or is it?

#2 CasiOo  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 996
  • View blog
  • Posts: 2,212
  • Joined: 05-April 11

Re: Error checking, or is it?

Posted 02 March 2012 - 09:38 AM

I made it fail, do I get a price :o ?

    public static void main(String[] args)
    {
    	System.setIn(null);
        int myInt;
        double myDouble;
        System.out.print("Please enter an integer: ");
        myInt = getValueExpectInt();
        System.out.print("Pleas enter a double: ");
        myDouble = getValueExpectDouble();
        
        System.out.println("Your int: " + myInt);
    }


Was This Post Helpful? 0
  • +
  • -

#3 Dorito_125  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 88
  • Joined: 13-December 08

Re: Error checking, or is it?

Posted 02 March 2012 - 09:46 AM

View PostCasiOo, on 02 March 2012 - 09:38 AM, said:

I made it fail, do I get a price :o ?

    public static void main(String[] args)
    {
    	System.setIn(null);
        int myInt;
        double myDouble;
        System.out.print("Please enter an integer: ");
        myInt = getValueExpectInt();
        System.out.print("Pleas enter a double: ");
        myDouble = getValueExpectDouble();
        
        System.out.println("Your int: " + myInt);
    }




Prize? haha, to feel accomplished!

But really, in order to improve my code is there a way to make it fail without changing the code? As if you were a user?

This post has been edited by Dorito_125: 02 March 2012 - 09:47 AM

Was This Post Helpful? 0
  • +
  • -

#4 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Error checking, or is it?

Posted 02 March 2012 - 02:01 PM

Hmm, if you use a try catch and it throws the exception then any variables given a value in it will be returned back to normal value. Like it didn't happen. Also, you do not need the line - Integer.valueOf(_temp).getClass().getName().equals("java.lang.Integer");

Hows this -
int num = -1;
do{
	try
	{
		num = in.nextInt();
	}catch(InputMismatchException e)
	{
		System.out.print("Incorrect format! Please enter in an proper integer: ");
	}
}while(num == -1);

Looks nicer to me. :)
Was This Post Helpful? 1
  • +
  • -

#5 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon

Reputation: 5440
  • View blog
  • Posts: 8,760
  • Joined: 19-March 11

Re: Error checking, or is it?

Posted 02 March 2012 - 02:41 PM

Yep, Fuzzy's is exactly what I'd do (except that it fails on input of -1... :) )

You could use a regex to validate int input, which would be a bit nicer except that runs into trouble since ints cannot take arbitrary values in Java. So you're trying to verify that it looks like an int - that's easy - and that looks like an int which is in the allowable range for integers. The latter is more difficult.

The funny thing is this is pretty much what the OP does. The reflection calls are gratuitous, as you'd see if the Exceptions in the catch block were explicitly stated. Put

System.out.println(ex.toString());


in the catch block and give it some bad input...

So, congratulations to the OP. De-obfuscate it and you'll find you've hit on the correct method of validating numeric input.

Performance note: We usually avoid creating gratuitous Exceptions because it causes a performance hit, but since it's in an input cycle, the machine is blocked by the user in any case, so performance is not a problem. If this were used to validate numbers coming in from a file, I'd be a little concerned, and I'd think a little more about using a regex to reject obviously non-int values.

This post has been edited by jon.kiparsky: 02 March 2012 - 02:43 PM

Was This Post Helpful? 0
  • +
  • -

#6 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Error checking, or is it?

Posted 02 March 2012 - 03:50 PM

In my defense, Of the 4294967294 possible Integer values to enter... (From -2147483648 to 2147483647)
I think they can forgive not being able to enter 1 of them in this case! :P

Yeah it does basically the same thing except his way is like wanting a variable with default value of 10, so he makes 2 more variables of value of 5 and adds them together instead of just setting it to 10. Really round about way of accomplishing the same thing.

Honestly I haven't really learned Regex yet so I didn't use that. Know what it is and does just haven't taught myself it yet.

This post has been edited by Fuzzyness: 02 March 2012 - 03:59 PM

Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8032
  • View blog
  • Posts: 31,202
  • Joined: 06-March 08

Re: Error checking, or is it?

Posted 02 March 2012 - 04:09 PM

View PostDorito_125, on 02 March 2012 - 11:46 AM, said:

But really, in order to improve my code is there a way to make it fail without changing the code?

Doing what ? Changing the compiler or the OS ?
Was This Post Helpful? 0
  • +
  • -

#8 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon

Reputation: 5440
  • View blog
  • Posts: 8,760
  • Joined: 19-March 11

Re: Error checking, or is it?

Posted 02 March 2012 - 04:25 PM

View PostFuzzyness, on 02 March 2012 - 05:50 PM, said:

In my defense, Of the 4294967294 possible Integer values to enter... (From -2147483648 to 2147483647)
I think they can forgive not being able to enter 1 of them in this case! :P

Yeah it does basically the same thing except his way is like wanting a variable with default value of 10, so he makes 2 more variables of value of 5 and adds them together instead of just setting it to 10. Really round about way of accomplishing the same thing.

Honestly I haven't really learned Regex yet so I didn't use that. Know what it is and does just haven't taught myself it yet.


As I say, I'd only really want to use regex for file input. Basically, what I'd do would be to filter it through a regex that recognizes a series of digits, with an optional initial +/- (no need to recognize the optional trailing l/L, unless the requirements say they want a Java int). That'll eliminate things with non-digits in them, but it'll pass some non-valid numbers (2147483648, for example) so we want to then use parseInt anyway. This way, I catch most of my bad input the quick way, and raise fewer Exceptions. I haven't tried this, so I don't know if it would actually save appreciable time. Exercise for the reader, and all that.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1