[英]Splitting A String Into An Array Of Words To Be Called Again
这是我到目前为止的代码
import java.util.*;
import java.io.*;
public class USconstitution
{
public static void main(String [] args) throws Exception
{
Scanner inFile = new Scanner(new File("constitution.txt"));
int x = 0;
int keyword1 = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a word from the keyboard");
String input = keyboard.next();
while(inFile.hasNext())
{
String word = inFile.next();
x++;
if(input.equalsIgnoreCase(word))
keyword1++;
}
//System.out.println("\n" + x);
System.out.println("The constitution has " + x + " words");
System.out.println("The first keyword shows up " + keyword1 + " times in the
constitution");
}
}
如此遥远的输出 =
从键盘输入单词
主席
宪法有4610个字
第一个关键字在宪法中显示20次
我对该程序的目标是搜索提供给我的包含美国宪法的文本文件。
第一部分简单地计算了文本文件中有多少个单词,接下来我要尝试的是让人们搜索某些关键字并让其搜索文本文件并说出该单词出现了多少次。
我正在考虑让提示询问用户希望输入哪些关键字,并使用split方法将每个单词创建为单独的字符串,然后在文件中搜索该单词,然后输出它出现多少次。 尽管我不确定该如何进行,但是任何帮助将不胜感激!
尝试这个:
public static void main(String[] args)
{
String text = "the quick brown fox jumps fox fox over the lazy dog brown";
String[] textArray = text.split(" ");
String[] keysToSearch = {"the", "fox", "dog"};
int count = 0;
System.out.println(text);
for(String key: keysToSearch)
{
for(String s : textArray)
{
if(key.equals(s))
{
count++;
}
}
System.out.println("Count of ["+key+"] is : "+count);
count=0;
}
}
输出:
the quick brown fox jumps fox fox over the lazy dog brown
Count of [the] is : 2
Count of [fox] is : 3
Count of [dog] is : 1
将执行check方法的代码移出main方法,然后将其放入使用单个关键字作为参数的单独方法中。 然后,您可以使用以下命令拆分控制台提供的输入字符串:
String[] keywords = input.split(" "); // will split at spaces
然后,您要做的就是遍历数组中的所有关键字
for(int i = 0; i < keywords.length; i++){
yourCountMethod(keywords[i]);
}
这只是一般性的想法,显然,您必须更改代码以适合。
希望有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.