当写判断一串字符中的空格、数字、字母、以及其它字符的个数 时,发现当遇到空格时就会出现问题,并且空格个数无法计算。
public class test3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str;
char c;
int number=0,ch = 0,space=0,other=0;
System.out.println("请输入一行字符");
str = scan.next();
for(int i = 0;i<str.length();i++) {
c=str.charAt(i);
if(c>='a'&&c<='z'||c>='A'&&c<='Z') {
ch++;
}
else if(c==' ') {
space++;
}
else if(c>='0'&&c<='9') {
number++;
}else {
other++;
}
}
System.out.println("英文字母有:"+ch+"空格有"+space+"数字有"+number+"其它字符有"+other);
}
}
改程序写过多次,然后发现网上代码如下:
public class test3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str;
char c;
int number=0,ch = 0,space=0,other=0;
System.out.println("请输入一行字符");
str = scan.nextLine();
for(int i = 0;i<str.length();i++) {
c=str.charAt(i);
if(c>='a'&&c<='z'||c>='A'&&c<='Z') {
ch++;
}
else if(c==' ') {
space++;
}
else if(c>='0'&&c<='9') {
number++;
}else {
other++;
}
}
System.out.println("英文字母有:"+ch+"空格有"+space+"数字有"+number+"其它字符有"+other);
}
}
仔细观察改动位置为将scan.next()改为了scan.nextLine()
后来经过查询明白了二者区别,scan.next()为遇见有效字符时开始,在遇到空格tab 回车时结束
所以当空格在中间时,空格后面的识别不到故空格后面的为无效,而scan.nextLine()可以识别任何字符