Programming easy question

How, in java, can I verify a user's input to be the correct type for the variable that stores it. In other words I want the program to keep asking the user for input until they use the correct type ie String.Thanks
[229 byte] By [datawerda] at [2007-11-26 18:50:27]
# 1
Every user input is a String.The question is can it also be parsed as an int, double, Date, etc.Integer.parseInt, etc., can help with that. If they throw an exception, it can't be interpreted as an int, etc.
jverda at 2007-7-9 6:24:28 > top of Java-index,Java Essentials,New To Java...
# 2
I think I understand that, so what about when I want to ask the user for input, and only want to accept Y or N for the input?
datawerda at 2007-7-9 6:24:28 > top of Java-index,Java Essentials,New To Java...
# 3

> I think I understand that, so what about when I want

> to ask the user for input, and only want to accept Y

> or N for the input?

There are a number of ways. If you just want to keep looping until they give y or n, here's one simple way.

boolean gotGoodInput;

do {

if ("Y".equalsIgnoreCase(input) {

do yes stuff

gotGoodInput = true;

}

else if ("N".equalsIgnoreCase(input)) {

do no stuff

gotGoodInput = true;

}

else {

gotGoodInput = false;

} while (!gotGoodInput);

jverda at 2007-7-9 6:24:28 > top of Java-index,Java Essentials,New To Java...
# 4
You can put them in try/catch block and if the data type is not withing the predefined data type, then just throw the exception.Or you can also check for the type manually, and keep this code in loop. If it finds the true data type then just break from the loop.
KeDeSola at 2007-7-9 6:24:28 > top of Java-index,Java Essentials,New To Java...