计算单词输入的次数 [英] counting the number of times a word is typed in
本文介绍了计算单词输入的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现了一个类似我的问题的解决方案:
import java.util.Scanner;
public class Counter
{
public static void main(String args [])
{
String a =,b =;
Scanner s = new Scanner(System.in);
System.out.println(输入字符串:);
a = s.nextLine();
while(b.length()!= 1)
{
System.out.println(输入单个字符:);
b = s.next();
}
int counter = 0;
for(int i = 0; i {
if(b.equals(a.charAt(i)+))
counter ++;
}
System.out.println(Number of occurrences:+ counter);
}
}
此程序仅计算选定字母的次数出现。我需要做同样的,但用一个完整的词。我如何修改这个代码来做我需要的呢?我不是最伟大的编程。您的帮助非常感谢。感谢!
解决方案
您可以使用拆分字符串
您可以拆分在空格上的字符串如
String [] words = a.split();
然后循环使用
for(String word:words){
if(word.equals(testWordToCompare)
counter ++;
}
}
因此,您的新代码将如下所示:
code> import java.util.Scanner;
public class Counter
{
public static void main(String args [])
{
String a = ,testWordToCompare =exists;
Scanner s = new Scanner(System.in);
System.out.println(Enter a string:);
a = s.nextLine();
String [] words = a.split();
int counter = 0;
for(String word:words){
if (word.quals(testWordToCompare)
counter ++;
}
}
System.out.println(+ testWordToCompare +的出现次数是:+ counter);
}
}
i found a solution similar to my problem here:
import java.util.Scanner;
public class Counter
{
public static void main ( String args[] )
{
String a = "", b = "";
Scanner s = new Scanner( System.in );
System.out.println( "Enter a string: " );
a = s.nextLine();
while ( b.length() != 1 )
{
System.out.println( "Enter a single character: " );
b = s.next();
}
int counter = 0;
for ( int i = 0; i < a.length(); i++ )
{
if ( b.equals(a.charAt( i ) +"") )
counter++;
}
System.out.println( "Number of occurrences: " + counter );
}
}
this program only counts the amount of times a selected letter appears. i need to do the same but with an entire word. How would i modify this code to do what I need it to? I'm not the greatest at programming. Your help is greatly appreciated. Thanks!
解决方案
You can use split string
You can split the string on space like
String[] words =a.split(" ");
Then loop through it like
for(String word : words) {
if(word.equals(testWordToCompare)
counter++;
}
}
So your new code would look like :
import java.util.Scanner;
public class Counter
{
public static void main ( String args[] )
{
String a = "", testWordToCompare = "exist";
Scanner s = new Scanner( System.in );
System.out.println( "Enter a string: " );
a = s.nextLine();
String[] words =a.split(" ");
int counter = 0;
for(String word : words) {
if(word.equals(testWordToCompare)
counter++;
}
}
System.out.println( "Number of occurrences of " + testWordToCompare +" is : " + counter );
}
}
这篇关于计算单词输入的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文