[英]JAVA: Count each word on a String, and count each letter on the words
因此,我有一個Java作業,其中有一個帶短語的String。 我需要計算該短語具有的每個單詞,然后計算每個單詞有多少個字母。 我已經能夠使用Tokenizer將短語分解為單詞,然后使用.countTokens()計數並打印單詞的數量。 但是,我無法計算每個單詞中的字母。
基本上,輸出應該是這樣的:
“ Nihil veritas est”
字數:3
Nihil:5個字母
Veritas:7個字母
Est:3個字母
到目前為止,這是我的代碼:
public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
StringTokenizer stoken = new StringTokenizer(phrase);
System.out.println("Your phrase has "+stoken.countTokens()+"words");
}
嘗試這個:
public class words {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
String[] words = phrase.split(" ");
System.out.println("The number of words is:"+words.length);
for(int i=0; i<words.length; i++){
System.out.println(words[i]+" is "+words[i].length()+" letters long.");
}
}
}
此代碼使用split()
代替Tokenizer
。 在我看來,這似乎更容易。
嘗試這個:
import java.util.Scanner;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("PLease enter your phrase");
String phrase = in.nextLine();
StringTokenizer st = new StringTokenizer(phrase);
System.out.println("Your phrase has " + st.countTokens() + " words");
// Loop thorough to count number of letters in each word.
while (st.hasMoreTokens()) {
String tokenName = st.nextToken();
System.out.println(tokenName + ": has " + tokenName.length() + " letters");
}
}
}
這是我為您解決的問題:
public static void main(String[]args) {
Scanner in = new Scanner(System.in);
System.out.println("Please type a phrase.");
String phrase= in.nextLine();
// get an array each having a word using split
String[]words = phrase.split(" ");
//print count of words?
System.out.println("Words: "+words.length);
//loop over the words
for(int i = 0; i < words.length; i++)
{
System.out.println(words[i]+": "+words[i].length()+" letters");
}
}
public class wordCount
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println(" Enter a String1");
String str=sc.nextLine();
System.out.println(" Entered String : ");
System.out.println(str);
//logic
char ch[]=str.toCharArray();
str="";
int count=0;
for (int i = 0; i < ch.length; i++)
{
if(ch[i]!=' ')
{
str=str+ch[i];
count++;
}
else if(ch[i-1]!=' ')
{
/*str=str+"-->"+count +" ";*/
System.out.println(str+"--->"+count);
count=0;
str="";
}
}
System.out.println(str+"--->"+count);
sc.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.