我的代码逻辑的下一步一直有问题。基本上,我应该检查文件的每一行,在同一行上寻找连续的标记,并打印重复的标记及其连续出现的次数。不重复的标记不打印。下面是一个示例文件
/*
* 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);
}
}
}
从这里开始任何对逻辑的见解将不胜感激。
给你,伙计,它应该为你工作
public Map<String, Long> scan(File file) throws Exception {
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;
}
伪代码:
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
}
}
}
你想创建一个符号频率表:
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);
}
就是这样。现在,您将获得已解析的所有符号的计数。