日期:2014-05-20  浏览次数:20800 次

输入只能为中文字符和英文
输入只能为中文字符和英文

------解决方案--------------------
Java code

public class TestInputIsChineseOrEnglish {
    public static void main(String[] args) {
    String string = null;
    Scanner scanner = new Scanner(System.in);
    do{
     string= scanner.nextLine();
    for(int i=0; i<string.length(); i++)
        if(isEnglish(string.charAt(i)) == false && isChinese(string.charAt(i)) == false){
        System.out.println("error");break;}
    System.out.println("correct");
    
    }while(string.equals("exit") == false);//要退出请输入exit
    
    }


    public static boolean isEnglish(Character c){
    return c.toString().matches("\\p{ASCII}");//0---127
    }
    
    public static boolean isChinese(char c) {
    Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
    if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
        || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
        || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
        || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION//""
        || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION//.
        || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {//,
        return true;
    }
    return false;

    }
}

------解决方案--------------------
k3...好厉害!我来解释下
主函数输入一行字符
进入判断
把字符串里字符一个一个取出来charAt(i)
用正则判断是否为英文isEnglish(Character c),是否为中文isChinese(char c)
如果是英文或者中文字符的话打印correct,否则打印error。
不过我觉得英文匹配"[a-zA-Z]+"合适点