Reputation: 11
So, I've been working on this problem for a few hours now, and I've scanned the internet extensively. I cannot figure out why this is not working for the life of me. When I enter numbers, it prompts me to re-enter, which is correct. However, when you type in a string ("FJASFJ") it still asks me to re-enter the information, I've been print.ln to see where the program is messing up and I'm still stuck :/
import javax.swing.JOptionPane;
public class functions {
private static boolean x;
private static String name;
private static String fur;
private static Number weight;
public static void nameExceptionFunc(String startName){
if(!(startName instanceof String)){
name=startName;
}else{
x=false;
while(x==false){
System.out.println("Sorry, but that is not an acceptable string.");
startName=JOptionPane.showInputDialog("Re-enter an acceptable value for your cat's name: ");
if(!(startName instanceof String)){
System.out.println("o");
name=startName;
break;
}else{
System.out.println("i");
continue;
}
}
}
}
Upvotes: 0
Views: 51
Reputation: 1420
showInputDialog
always returns a string, even if it's given numerical input (the string just contains a bunch of numbers). Therefore startName instanceof String
is always true. Thus, the else-branch of the if-statement is taken, and the program continues to loop.
Instead, you'll need to decide more specifically what kind of strings you want to accept. For example, is any string that doesn't contain numbers okay? A straightforward (but probably not best) way would be to loop through the characters of the string and check if each one is okay. It would be good to write that as a separate function. Then instead of startName instanceof String
you could call checkName(startName)
or something like that.
Upvotes: 2