java经典问题_对输入进行统计

来源:互联网 发布:不锈钢行情走势软件 编辑:程序博客网 时间:2024/06/06 03:50

先看下怎么获得从键盘的输入,两种方式,使用Scanner 和BufferedReader,

Scanner:Scanner取得输入的依据是空格符,包括空格键,Tab键和Enter键.当按下这其中的任一键 时,Scanner就会返回下一个输入(scanner.nextLine()可以获得包含空格的输入). 使用Scanner就不能完整的获得你输入的字符串。

BufferedReader: 它的readLine()方法会返回用户在按下Enter键之前的所有字符输入,使用它的时候需要catch IOException.

public class PractiseInput {private void getInput(){Scanner scan = new Scanner(System.in);System.out.println("请输入您的姓名:");String name = scan.nextLine();System.out.println("请输入您的年龄:");int age = scan.nextInt();System.out.println("请输入float");float salary = scan.nextFloat();System.out.println("name="+name+" age="+age+" salary="+salary);InputStreamReader reader = new InputStreamReader(System.in);BufferedReader input = new BufferedReader(reader);try {System.out.println("请输入:");String text = input.readLine();System.out.println("您的输入:"+text);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args) {(new PractiseInput()).getInput();}}

属于数字的正则表达式:^[0-9]*$ (不能匹配出全角的时候输入的数字,^[\uFF10-\uFF19]*$

匹配中文字符的正则表达式: [/u4e00-/u9fa5]

匹配由26个英文字母组成的字符串:^[A-Za-z]+$              ( 匹配全角时的英文字母:\uFF41-\uFF5A\uFF21-\uFF3A)

匹配空格:要同时匹配 \s 以及各种其他的空白字符(包括全角空格等),可以使用:[\\s\\p{Zs}]

\s 只能匹配下面六种字符:
半角空格( )
水平制表符(\t)
竖直制表符
回车(\r)
换行(\n)
换页符(\f)

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。 

public class Practise7 {int charCount = 0;int numCount = 0;int blankCount = 0;int otherCount = 0;int chineseCount = 0;private static final String E1 = "^[A-Za-z\uFF41-\uFF5A\uFF21-\uFF3A]+$";//英文字母private static final String E2 = "^[0-9\uFF10-\uFF19]*$";//数字private static final String E3 = "[\\s\\p{Zs}]";//空格private static final String E4 = "[\u4e00-\u9fa5]";//中文private void getResult(){InputStream input = System.in;Scanner scan = new Scanner(input);System.out.println("请您输入:");String userInput = scan.nextLine();char[] userInputArray = userInput.toCharArray();String[] userInputStr = new String[userInputArray.length];for(int i = 0; i < userInputArray.length; i++){userInputStr[i] = String.valueOf(userInputArray[i]);if(userInputStr[i].matches(E1)){charCount++;}else if(userInputStr[i].matches(E2)){numCount++;}else if(userInputStr[i].matches(E3)){blankCount++;}else if(userInputStr[i].matches(E4)){chineseCount++;}else{otherCount++;}}System.out.println("userInput="+userInput);System.out.println("charCount="+charCount);System.out.println("numCount="+numCount);System.out.println("blankCount="+blankCount);System.out.println("chineseCount="+chineseCount);System.out.println("otherCount="+otherCount);}public static void main(String[] args) {(new Practise7()).getResult();}}


写一个小函数取你所需要的字符的UNICODE码,然后构造出需要的正则表达式


原创粉丝点击