import java.util.Scanner;
public class UserInput {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean alpha = false;
boolean numeric = false;
boolean accepted = true;
boolean underscore=false;
Scanner s = new Scanner(System.in);
System.out.println("please Enter an Idintifire: " +s);
char c = s.next().trim().charAt(0);
if (Character.isDigit(c))
{
numeric = true;
} else if (Character.isLetter(c))
{
alpha = true;
}
else if (Character.isUnicodeIdentifierPart(c))
{
underscore = true;
}
else
{
accepted = false;
}
if (accepted && alpha && numeric && underscore)
{
System.out.println("this is an idintifire " +c);
}
else {
System.out.println(c+ " this not an idintifire ");
}
s.close();
}
}
输出:
please Enter an Idintifire: java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
我希望用户只输入一个字母数字字;例如,(ab_23)不是(ab 23)
有什么建议吗?
答案 0 :(得分:0)
Scanner s = new Scanner(System.in);
System.out.println("please Enter an Idintifire: " +s);
您正在上面的行中打印您创建的扫描仪对象的值。尝试删除print语句中的s。
System.out.println("please Enter an Idintifire: ");
修改强>
Scanner s = new Scanner(System.in);
System.out.println("please Enter an Idintifire: ");
String input = s.next();
for(int i=0;i< s.length();i++){
char c = input.charAt(i);
if (Character.isDigit(c))
{
numeric = true;
} else if (Character.isLetter(c))
{
alpha = true;
}
else if (Character.isUnicodeIdentifierPart(c))
{
underscore = true;
}
else
{
accepted = false;
}
}
if (accepted && alpha && numeric && underscore)
{
System.out.println("this is an idintifire " +input);
}
else {
System.out.println(input+ " this not an idintifire ");
}