4

我的代码逻辑的下一步一直有问题。基本上我应该检查文件的每一行,在同一行上寻找连续的标记,并打印重复的标记以及它连续出现的次数。不打印不重复的标记。这是一个示例文件

/*
 * 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);
        }
    }
}

从这里开始对逻辑的任何见解将不胜感激。

4

3 回答 3

1

pseudocode:

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
  }
 }
}
于 2013-01-22T01:29:14.017 回答
1

给你,伙计,它应该对你有用

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;
}
于 2013-01-22T03:42:40.650 回答
0

You want to make a symbol frequency table:

Map<String, Integer> symbolFrequencies = new HashMap<String, int>();

Then for each symbol, do this:

Integer countForSymbol = symbolFrequencies.get(symbol);
if (countForSymbol==null){
    symbolFrequencies.put(symbol, 1);
} else {
    countForSymbol = new Integer(countForSymbol.intValue + 1);
}

and that's it. You will now have counts for all the symbols you have parsed.

于 2013-01-22T01:29:41.590 回答