Link to home
Start Free TrialLog in
Avatar of ms_lost
ms_lost

asked on

Input Validation

how to restrict the user to enter Integer only not float..
Avatar of pellep
pellep
Flag of Sweden image

'enter' in what context. Enter from commandline? Enter in a textfield?

You could do like this
(only an example)
// -->
        String sVal = "1.1123";
        try {
            Integer iVal = Integer.valueOf(sVal);
        } catch (NumberFormatException nfe) {
            System.out.println("ERROR. Input " + sVal + " not an integer!!!");
        }
// <--

sVal here represents your user-input and you put your specific errorhandling in the catch phrase.
mlost,

Can the user enter numbers like 123.0 or 0.0?
Avatar of ms_lost
ms_lost

ASKER

i tried it it's not working.. it says incompatible types Integer

System.out.println(" Enter the Mileage");
String sVal=Keyboard.readString();
try {
int mileage = int.valueOf(sVal);
} catch (NumberFormatException nfe) {
System.out.println("ERROR. Input " + sVal + " not an integer!!!");
            }
}

int mileage.is used as a parameters in sub classes.. plz try to answer as soon as possible
replace this:
int mileage = int.valueOf(sVal);
with this:
int mileage = Integer.parseInt(sVal);

and don't change anything
Avatar of ms_lost

ASKER

thanks alot..it worked perfect..but how to change the Error msg
Is this what you want:
while (true) {
  System.out.println("Enter the Mileage");
  String sVal=Keyboard.readString();
  try {
    int mileage = int.valueOf(sVal);
    break;
  } catch (NumberFormatException nfe) {
    System.out.print("Not an integer. ");
  }
}

If not - be more specific
ops - sorry:

int mileage;
while (true) {
 System.out.println("Enter the Mileage");
 String sVal=Keyboard.readString();
 try {
   mileage = Integer.parseInt(sVal);
   break;
 } catch (NumberFormatException nfe) {
   System.out.print("Not an integer. ");
 }
}


Avatar of ms_lost

ASKER

ok thanks..can u plz explain for me the  :

while (ture)
try
catch(format....)


cuz they are new terms for me.. plz..and i'll add 45 points for that question
ASKER CERTIFIED SOLUTION
Avatar of Venci75
Venci75

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial