scan.nextLine()与scan.next()的区别 当写判断一串字符中的空格、数字、字母、以及其它字符的个数

本文档详细介绍了如何修复一个Java程序,该程序在计算字符串中空格、数字、字母和其他字符数量时遇到问题。通过对比`next()`与`nextLine()`的区别,解决了空格识别问题,确保了所有字符都被计入统计。
摘要由CSDN通过智能技术生成

当写判断一串字符中的空格、数字、字母、以及其它字符的个数  时,发现当遇到空格时就会出现问题,并且空格个数无法计算。

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()可以识别任何字符

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值