I am creating a console game.. and I want the players to be able to choose their own usernames. Having usernames like .-|\12b-}|can be really weird. I want to be able to check if the username has "special characters" in it. If the player has a special character in his/her username, I want the system to print out a message(something like: Please change your username) . I don't want the code to just replace the letters.
Here is an example(follow this if you have an answer):
import java.util.Scanner;
class StackOverflowExample {
public static void main(String[] args) {
System.out.println("Welcome New Player! What will your name be?");
Scanner userInteraction = new Scanner(System.in);
String userInput = userInteraction.nextLine();
System.out.println("Welcome " + userInput + "!");
}
}
Output :
You can see why this would be super weird..
I want to be able to scan:
String userInput = userInteraction.nextLine();
for any weird characters. How would I go about scanning the String?
Edited to have correct java code
You can check what each letter in a string is by using a int-asted charAt
call to return the # the character is in ASCII [See here] ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt )
public static boolean isAlphaNumeric(String str) {
int code, i, len;
len = str.length();
for (i = 0; i < len; i++) {
code = (int) str.charAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
public static void main(String[] args) {
String userInput = userInteraction.nextLine();
if(isAlphaNumeric(userInput )){
System.out.println("Welcome New Player! What will your name be?");
Scanner userInteraction = new Scanner(System.in);
String userInput = userInteraction.nextLine();
System.out.println("Welcome " + userInput + "!");
}
else{
System.out.println("Change your name from" + userInput + "!");
}}
Try this. It continues to prompt for a username if anything other than letters are provided. Usernames like Battle101 or ~Hello~ are not allowed.
Scanner userInteraction = new Scanner(System.in);
String userInput = "";
while (true) {
System.out.println("Welcome New Player! What will your name be?");
userInput = userInteraction.nextLine();
if (userInput.matches("[a-zA-Z]+")) { // check that the input only contains letters
// okay so exit loop
break;
}
// else explain the problem and reprompt.
System.out.println("Only alphabetic characters are permitted.\nPlease try again.");
}
System.out.println("Welcome " + userInput + "!");
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.