简体   繁体   English

从 java.util.Scanner 读取字母数字用户输入时出现 InputMismatchException

[英]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例如: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.如果您这样做,您将遇到InputMismatchException 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]+", "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Java 中的 java.util.Scanner 时出现 InputMismatchException - InputMismatchException when working with java.util.Scanner in Java 模拟java.util.Scanner的用户输入 - Emulating user input for java.util.Scanner 如何使用java.util.Scanner正确扫描用户输入? - How to properly scan for user input using java.util.Scanner? 使用java.util.scanner读取和解析文件 - Reading and parsing a file with java.util.scanner 如何使用 java.util.Scanner 从 System.in 正确读取用户输入并对其采取行动? - How to use java.util.Scanner to correctly read user input from System.in and act on it? 从 System.in 读取时,如何防止 java.util.Scanner 抛出 NoSuchElementException? - How can I prevent java.util.Scanner from throwing NoSuchElementException when reading from System.in? 使用java.util.Scanner从文件中读取字符串并使用换行符作为分隔符时,字符串的行为异常 - Strings act weirdly when reading them from a file with the java.util.Scanner and using linebreaks as delimiter 如何只从 java.util.Scanner 获取一个输入? - How to take only a single input from java.util.Scanner? java.util.Scanner:等待输入 - java.util.Scanner: wait for input 使用scanner,java.util.InputMismatchException从文件读取double - reading double from a file using scanner, java.util.InputMismatchException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM