简体   繁体   中英

InputMismatchException when reading alphanumeric user input from java.util.Scanner

import java.util.Scanner;

public class StrinExp {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        int i = 0;
        String a = null;
        System.out.println("Enter username");
        i=scanner.nextInt();
        a=a.valueOf(i);
        System.out.print(a);
    }
}

But m getting error when i am giving a alphanumeric value..

ex: Manish0818

and even when i am giving same value as string, still facing the same problem.

Help

change your input statement.

String a = null;
System.out.println("Enter username");
a = scanner.next();
System.out.println(a);

If there's an alphanumeric, then take it in as a string, not as an integer. You will land in an InputMismatchException if you do so. It means that you're trying to take an integer but you are entering a string which differ in data types.

and if you wish to remove all junk characters except alphanumeric then you can try

a = a.replaceAll("[^a-zA-Z0-9]+", "");

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