我的代码逻辑中的下一步遇到了问题。基本上我应该检查文件的每一行,在同一行上查找连续的令牌,并打印重复的令牌以及它连续发生的次数。不重复打印不重复的令牌。 这是一个示例文件
/*
* sometext.txt
* hello how how are you you you you
I I I am Jack's Jack's smirking smirking smirking smirking revenge
bow wow wow yippee yippee yo yippee yippee yay yay yay
one fish two fish red fish blue fish
It's the Muppet Show, wakka wakka wakka
*/
这是我写的一些代码。
package chapter6;
import java.util.*;
import java.io.*;
public class OutputDuplicates {
public static void main (String[] args) throws FileNotFoundException {
for (;;) {
Scanner scan = new Scanner(System.in);
prompt(scan);
}
}
public static void prompt(Scanner scan) throws FileNotFoundException {
System.out.println("What is the name of the file?");
String name = scan.next();
File inputFile = new File(name);
if (inputFile.exists()) {
Scanner read = new Scanner(inputFile);
while (read.hasNext()) {
String line = read.nextLine();
Scanner oneLine = new Scanner (line);
while (oneLine.hasNext()) {
String word = oneLine.next();
System.out.println(word);
}
}
} else if (!inputFile.exists()) {
prompt(scan);
}
}
}
对此逻辑的任何见解都将非常感激。
答案 0 :(得分:1)
伪代码:
for each line in the file
{
lastword = ""
numtimes = 1
for each word in the line
{
if word == lastword
{
numtimes++
}
else
{
if numtimes > 1
{
print (/*print lastword and numtimes here*/)
}
lastword = word
numtimes = 1
}
}
}
答案 1 :(得分:0)
您想制作符号频率表:
Map<String, Integer> symbolFrequencies = new HashMap<String, int>();
然后对于每个符号,执行以下操作:
Integer countForSymbol = symbolFrequencies.get(symbol);
if (countForSymbol==null){
symbolFrequencies.put(symbol, 1);
} else {
countForSymbol = new Integer(countForSymbol.intValue + 1);
}
就是这样。您现在将拥有已解析的所有符号的计数。
答案 2 :(得分:0)
在这里,你好友,它应该适合你
public java.util.Map scan(File file)抛出异常{
java.util.Map<String, Long> map = new HashMap<>();
Scanner read = new Scanner(file);
while (read.hasNext()) {
String line = read.nextLine();
if(map.containsKey(line)) {
map.put(line, map.get(line).longValue() + 1);
} else {
map.put(line, 1L);
}
}
return map;
}