简体   繁体   中英

For Java, if I want to do an if statement to make sure the input only takes in one character, how should I proceed?

I am trying to do a while loop to get user input and make sure what they put is a character only, so if they do ab, it will ask them to do another user input instead of taking the first letter they entered as an answer. Can I do this with a try catch such as the one below? It is not working right now and I am not sure why.

Thanks for your help!

            boolean single = true;
        
                while(single) {
                
                    try {
                        if(letter.length()==1) {
                            break;
                        } else {
                            System.out.println("Please enter a single character only!");
                        }
                    } catch (Exception e) {
                      System.out.println("Please enter a single character only!");
                    }
                }

I am trying to do a while loop to get user input and make sure what they put is a character only, so if they do ab, it will ask them to do another user input instead of taking the first letter they entered as an answer. Can I do this with a try catch such as the one below? It is not working right now and I am not sure why.

Thanks for your help!

            boolean single = true;
        
                while(single) {
                
                    try {
                        if(letter.length()==1) {
                            break;
                        } else {
                            System.out.println("Please enter a single character only!");
                        }
                    } catch (Exception e) {
                      System.out.println("Please enter a single character only!");
                    }
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM