我正在尝试从用户键入的文件中读取字母数,在这种情况下为“ cyphertext.txt”。我遇到的问题是,不是输出文件中有94个“ E”或27个“ Z”,而是输出文件名的字母数,因此“ ciphertext.txt”具有2个“ T” s。 (这是用BlueJ编码的)
这是频率测试器中的代码:
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
public class FrequencyTester
{
public static void main(String[] args) throws IOException
{
//freq.findFile();
Scanner in = new Scanner(System.in);
String fileNameStr = "";
while(! (new File (fileNameStr + ".txt").isFile()))
{
System.out.print("Please input the name of your desired file (no file extension required): ");
fileNameStr = in.next() + in.nextLine();
if(new File (fileNameStr + ".txt").isFile())
{
System.out.println("\nFile accepted.");
Frequency freq = new Frequency(fileNameStr);
Scanner inFile = new Scanner(fileNameStr + ".txt");
freq.fileWords(inFile);
freq.frequencyPrinter();
}
else
{
System.out.println("\nError: Invalid File Name");
}
}
}
}
这是频率中的代码:
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
public class Frequency
{
// instance variables - replace the example below with your own
private int x;
private String fileNameStr, oneWord, oneChar;
public final char [] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
public int [] alphaCounter = new int[alphabet.length];
/**
* Constructor for objects of class Frequency
*/
public Frequency(String fileNameStr) throws IOException
{
// initialise instance variables
//File fileName = new File (fileNameStr + ".txt");
PrintWriter outFile = new PrintWriter(new File(fileNameStr +"Frq.txt"));
//Scanner inFile = new Scanner(fileName);
for(int h = 0; h < alphaCounter.length; h++)
alphaCounter[h] = 0;
}
public void fileWords(Scanner inFile)
{
while(inFile.hasNext())
{
oneWord = inFile.next();
System.out.println(oneWord);
for(int i = 0; i < oneWord.length(); i++)
{
if(!Character.isWhitespace(oneWord.charAt(i)))
charCounter(i);
}
}
}
public void charCounter(int i)
{
for(int j = 0; j < alphabet.length; j++)
{
if(oneWord.charAt(i) == alphabet[j])
{
alphaCounter[j]++;
}
}
}
public void frequencyPrinter()
{
System.out.print("\n");
for(int k = 0; k < alphabet.length; k++)
{
System.out.print(alphabet[k] + " - " + alphaCounter[k] + "\n");
}
}
}
这是BlueJ中的设置和输出: