![]() |
How to compare variable types in Java
How do I compare types in Java?
I'm doing input checking for the following code :
do {:
} while (((increase < 0) || (increase > 105)) || (typeof(increase) != typeof(Integer)));Thanks for your time, Anthony Christe |
Re: How to compare variable types in Java
Can you elaborate yourself a bit more? But whatever you have given right now it can be solved by exception handeling. I am not a master of exception handeling but if you send those two inputs as arguements to a method, you can use IllegalArgumentException.
|
Re: How to compare variable types in Java
Assuming the increase variable in the code you posted is a Scanner, you can either use the hasNextInt() method to determine if the data waiting to be read can be interpreted as an int value, or catch an exception.
|
Re: How to compare variable types in Java
you mean making sure you dont add a float to an int? java will auto cast so it works as a float.
|
Re: How to compare variable types in Java
the method getClass() will tell you the class.
|
Re: How to compare variable types in Java
but the main requirement is that to tell explicitely to user that the data entered by user for two different variables is not of same type. Implicite conversion will take place, but he wants that if types are not same the program should not go to evaluation sothere should not be any type casting.
|
Re: How to compare variable types in Java
you can do something:
increase.getClass().getName() |
Re: How to compare variable types in Java
There is absolutely no reason to use getClass(). Scanner.nextInt() will either return an int or throw an exception. If you are reading that value into another type such as a float, that variable will be a float regardless of what the user enters.
|
Re: How to compare variable types in Java
You mis-located the change..
:
} while (((increase < 0) || (increase > 105)) || increase.getClass().getName().equals("java.lang.Integer); |
Re: How to compare variable types in Java
Yeah i first thought instanceof can be used.
instanceof i think can be used for objects only. |
| All times are GMT -5. The time now is 3:52 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC