0

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;
                }
            }   
        }
    }
3
  • Would you please describe what you want to do, I mean your business conditions. you want to allow to enter only numbers Commented Oct 6, 2017 at 5:34
  • I would like to only allow alpha characters. So, no numbers, symbols or anything else just the alphabet ("ABC") Commented Oct 6, 2017 at 5:47
  • To check the content of the input, you should not use instanceof. It is used to check the class type of the variable. You may try regular expression for your need. e.g. startName.matches("^[A-Za-z]*$") Commented Oct 6, 2017 at 5:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.