-1
我想找到一個句子中每個單詞的字母數。我已經嘗試了幾次使用幾個代碼,但從來沒有得到它。我總是顯示錯誤StringIndexOutOfBounds異常。我的一個代碼如下:java程序找到一個句子中每個單詞的字母數
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);
}
}
}
謝謝。你能給一個更簡單一點的程序,而不是使用數組嗎? –