[英]java program to find the number of letters of each word in a sentence
I want to find the number of letters of each word in a sentence.我想找到一个句子中每个单词的字母数。 I have tried several times using several codes but never got it.
我尝试了几次使用几个代码,但从未得到它。 I always shows the error StringIndexOutOfBounds Exception.
我总是显示错误 StringIndexOutOfBounds 异常。 One of my codes were as follows:
我的代码之一如下:
import java.util.*;
class LengthOfEachWord
{
public static void main()
{
Scanner sc = new Scanner(System.in);
String s,a,b;
int l,x,l1,y=0,now;
try
{
System.out.print("Enter a sentence:");
s=sc.nextLine();
l=s.length();
String arr[]=s.split(" ");
now=arr.length;
while(true)
{
x=s.indexOf(' ');
a=s.substring(0,x);
l1=a.length();
System.out.println(a+"="+l1);
b=s.substring(x+1,l);
s=b;
y++;
if(now==y)
{
break;
}
}//End of while block
}//End of try block
catch(Exception e)
{
System.out.println("Error="+e);
}
}
}
Try to split the word and by the iteration count the length of every element in the array尝试拆分单词并通过迭代计算数组中每个元素的长度
public static void main(String[] args) {
final Scanner myScanner = new Scanner(System.in);
String sentence;
System.out.print("Enter a sentence:");
sentence = myScanner.nextLine();
// now split by space
final String[] sentceComp = sentence.split(" ");
// loop over the words in sentence
for (int i = 0; i < sentceComp.length; i++) {
System.out.println("The word \"" + sentceComp[i] + "\" in the input sentence has " + sentceComp[i].length() + " chars");
}
}
Enter a sentence:
输入一句话:
java program to find the length of each word in a sentence
java程序找出句子中每个单词的长度
The word "java" in the input sentence has 4 chars
输入句子中的单词“java”有 4 个字符
The word "program" in the input sentence has 7 chars
输入句中的“程序”一词有 7 个字符
The word "to" in the input sentence has 2 chars
输入句子中的单词“to”有 2 个字符
The word "find" in the input sentence has 4 chars
输入句子中的单词“find”有 4 个字符
The word "the" in the input sentence has 3 chars
输入句子中的单词“the”有 3 个字符
The word "length" in the input sentence has 6 chars
输入句子中的单词“长度”有 6 个字符
The word "of" in the input sentence has 2 chars
输入句子中的单词“of”有 2 个字符
The word "each" in the input sentence has 4 chars
输入句子中的单词“each”有 4 个字符
The word "word" in the input sentence has 4 chars
输入句子中的单词“word”有 4 个字符
The word "in" in the input sentence has 2 chars
输入句子中的单词“in”有 2 个字符
The word "a" in the input sentence has 1 chars
输入句子中的单词“a”有 1 个字符
The word "sentence" in the input sentence has 8 chars
输入句子中的单词“sentence”有8个字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.