统计字符数,单词数,行数

这次的任务是完成字符数,单词数,行数的统计。做了一个demo。
运行结果:

解析代码:

private void analysi() throws IOException {
    int chars = 0;//字符数
    int words = 0;//单词数
    int lines = 0;//行数

    String filename=edt_content.getText().toString();
    String content=edt_content.getText().toString();
    InputStreamReader isr = null;
    try {
        isr = new InputStreamReader(new FileInputStream("/"+content+".txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    BufferedReader br = new BufferedReader(isr);
    while(br.read()!=-1)
    {
        String s = br.readLine();
        chars += s.length();
        words += s.split(" ").length;
        lines++;
    }
    isr.close();
    tv_jiexi.setText("单词数:"+words+",字符数:"+chars+",行数:"+lines);
}
}

自定义属性:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView tv_jiexi;
private EditText edt_content;
private Button btn_analysis;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
}

private void initView() {
    edt_content = (EditText) findViewById(R.id.edt_content);
    btn_analysis = (Button) findViewById(R.id.btn_analysis);
    tv_jiexi = (TextView) findViewById(R.id.tv_jiexi);
    btn_analysis.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_analysi:
            try {
                analysi();
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
    }
}

posted @ 2017-03-27 12:50  丨失眠症  阅读(160)  评论(0编辑  收藏  举报