菜鸟求高人指点,用java写的一个小程序,统计输入的空格字母数字,但是为什么无法统计空格呢,求高人指点

/*
* 接受任意输入的字符串,统计其中英文字母数字,其他符号,空格的数量
* 为什么输入空格就无法显示出来呢?无法统计空格
*/

package com.test2;
import java.util.*;
public class demo {

public static void main(String[] args) {
System.out.println("请输入字符串:");
Scanner sc=new Scanner(System.in);
String str=sc.next();
int countNum=0;
int countZm=0;
int countYy=0;
int countSpace=0;
int countOther=0;
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i);
if(c==' '){
countSpace++;
}else if((c>'a'&&c<'z')||(c>'A'&&c<'Z')){
countZm++;
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'
||c=='A'||c=='E'||c=='I'||c=='O'||c=='U'){
countYy++;
}

}else if(c>='0'&&c<='9'){
countNum++;
}else {
countOther++;
}
}
System.out.println("总共有数字:"+countNum+",英文字母:"+countZm+",总用有元音字母:"+countYy+",总共有空格:"+
countSpace+",其他符号:"+countOther);
}
}

改成String str = sc.nextLine();
你用next()方法读取的是一个字符,你这里要输入的是一行字符串,所以要用nextLine()方法把整行读进来。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-18
if(c==' ') 改为 if(c==' ')追问

我是在两个单引号之间家里空格,我统计空格时候加了个打印语句,发现根本程序没进去

追答

空格是分隔符,sc.next()不能取出空格。
程序需要修改,sc.next()改为sc.nextLine()。

第2个回答  2013-09-18
在统计前,打印出来看看还有没有空隔。
相似回答