5-26 单词长度 (15分)

5-26 单词长度   (15分)

你的程序要读入一行文本,其中以空格分隔为若干个单词,以.结束。你要输出每个单词的长度。这里的单词与语言无关,可以包括各种符号,比如it's算一个单词,长度为4。注意,行中可能出现连续的空格;最后的.不计算在内。

输入格式:

输入在一行中给出一行文本,以.结束

提示:scanf("%c",...);来读入一个字符,直到读到.为止。

输出格式:

在一行中输出这行文本对应的单词的长度,每个长度之间以空格隔开,行末没有最后的空格。

输入样例:

It's great to see you here.

输出样例:

4 5 2 3 3 4

思路:

我刚开始的想法是分割字符串,但是如果字母之间有很多空格的话,那么就会出现错误,但是经过更改之后,最后一个测试点是格式错误。如代码1

代码2是正确的,它是循环输入字符,因为字符sc.next()与字符之间不能有空格.所以就不用考虑输入之间的空格,只用考虑句首和句尾的空格。我这在网上找了几个测试数据  供大家参考。

  • ___________i 起始有空格
  • i    love. 有连续的空格
  •      . 单独一个点的情况。

代码1:

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		char[] a = new char[s.length()];
		int j = 0;
		String[] num = s.split(" ");
		for (int i = 0; i < s.length(); i++) {
			a[i] = s.charAt(i);
			if (a[i] == '.' && a[i - 1] == ' ') {
				j = 1;
			}
		}
		
		if (j == 1) {//句尾句号和单词之间有空格
			for (int i = 0; i < num.length - 1; i++) {
				if (num[i].length() != 0 && num[i] != ".") {
					if (i < num.length - 2) {
						System.out.print(num[i].length() + " ");
					} else if (i == num.length - 2) {
						System.out.println(num[i].length());
					}
				}
			}
		}else if(j == 0){//题目中的输入
			for (int i = 0; i < num.length; i++) {
				if (num[i].length() != 0 && num[i] != ".") {
					if (i < num.length - 1) {
						System.out.print(num[i].length() + " ");
					} else if (i == num.length - 1) {
						System.out.println(num[i].length()-1);
					}
				}
			}
		}

	}
}

上述代码在测试的时候最后一个测试点是格式错误,有谁知道什么原因的可以告诉我一下,谢谢。

代码2:

import java.util.Scanner;
public class Main{
	public static void main(String[] args){
    	Scanner sc = new Scanner(System.in);
    	int count = 0 ;
    	while(sc.hasNext()){//一直输入
    		String s = sc.next();
    		int l = s.length();
    		if(s.contains(".")){//判断输入的字符串中是否含有‘.’
    			count++;
    			l--;
    			if(l!=0&&count==1){
    				System.out.printf("%d",l);//输出时候和前面输出内容没有空格
    			}
    			else if(l!=0&&count!=1){
    				System.out.printf(" %d",l);//输出时候和前面输出内容有空格
    			}
    		}else{
    			count++;
    			if(count==1){
    				System.out.printf("%d",l);
    			}
    			else{
    				System.out.printf(" %d",l);
    			}
    		}
    	}
    }
}

这个代码是正确的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值