嗨,我有一个如下所示的java类,但是现在我可以调用main函数,并为其指定一个文本文件名称以在命令行窗口中使用,这样我的输入在命令行中将如下所示:Main .exe TextFile.txt
该类如下所示:
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
static ArrayList<Character> letters;
static ArrayList<Integer> lettersCount;
private static boolean caseSensitive = true;
public static void main(String[] args) {
// write your code here
letters = new ArrayList<Character>();
lettersCount = new ArrayList<Integer>();
loadFile(caseSensitive);
print(lettersCount, letters);
System.out.print("Enter: \n" +
"'1' to make it not case sensitive\n");
Scanner reader = new Scanner(System.in);
int input = reader.nextInt();
reader.close();
switch (input){
case 1:
caseSensitive = false;
loadFile(caseSensitive);
print(lettersCount, letters);
break;
default:
System.out.print("There was an error with your input.\n");
break;
}
}
public static void loadFile(boolean caseSensitive){
File file = new File("Text.txt");
if (!file.exists()) {
System.out.println("File does not exist.");
return;
}
if (!(file.isFile() && file.canRead())) {
System.out.println(file.getName() + " cannot be read from.");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
// System.out.print(current);
// System.out.print("\n");
if(caseSensitive == false){
current = Character.toUpperCase(current);
}
if(current != ' ' && current != '\n' && current != '\t' && current != '\r'){
int index = 0;
Boolean characterFound = false;
for (char character: letters) {
if(character == current){
lettersCount.set(index, lettersCount.get(index) + 1);
characterFound = true;
}
index++;
}
if(characterFound == false){
letters.add(index, current);
lettersCount.add(index, 1);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
/* int index = 0;
for (char character: letters) {
System.out.print(letters.get(index));
System.out.print(lettersCount.get(index).toString());
System.out.print("\n");
index++;
}*/
}
public static void print(ArrayList<Integer> lettersCount, ArrayList<Character> letters){
int totalLetterCount = 0;
for (int x = 0; x < lettersCount.size(); x++) {
totalLetterCount += lettersCount.get(x);
}
System.out.print("Total characters: " + totalLetterCount + "\n");
if (caseSensitive == true){
System.out.print("Most frequently used characters: (default: case sensitive) \n");
}
else {
System.out.print("Most frequently used characters: (not case sensitive) \n");
}
for(int numRankings = 0; numRankings < 10; numRankings++){
int mostFreqIndex = -1;
for (int x = 0; x < lettersCount.size(); x++) {
if(lettersCount.get(x) > mostFreqIndex){
mostFreqIndex = x;
}
}
System.out.print(numRankings + 1 + ". " + letters.get(mostFreqIndex) + " Times used: " + lettersCount.get(mostFreqIndex) + "\n");
letters.remove(mostFreqIndex);
lettersCount.remove(mostFreqIndex);
}
}
}