题3

来源:互联网 发布:淘宝手机架 编辑:程序博客网 时间:2024/05/17 05:08

统计一行字符中有多少个单词

import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner sc=new Scanner(System.in);        while(sc.hasNext()){            String str=sc.nextLine();            int word=0;            int count=0;            for (int i = 0; i <str.length() ; i++) {                if(str.charAt(i)==' '){                    word=0;                }else if(word==0){                    word=1;                    count++;                }            }            System.out.println(count);        }    }}