加载文本文档并根据重复单词的数量对它们进行排名的 Java 程序 - 不断获取文件未找到错误

Posted

技术标签:

【中文标题】加载文本文档并根据重复单词的数量对它们进行排名的 Java 程序 - 不断获取文件未找到错误【英文标题】:Java Program that loads text documents and ranks them based on amount of repeated words - keep getting file not found error 【发布时间】:2022-01-10 07:03:09 【问题描述】:

我正在创建一个 Java 程序,它可以加载不同的文本文档(在本例中,是四本不同小说的第一章左右),然后按照词汇排名的顺序将它们打印出来。换句话说,它们是根据章节中单词重复的次数来排名的。这个程序包括三个类:

hw5.java:

public class hw5 
    //main method
    public static void main(String[] args) throws FileNotFoundException 
        //stores user entered data
        String userInput = "";
        //Scanner class object created
        Scanner in = new Scanner(System.in);
        
        System.out.println("Write a file name to include in your ranks, '?' to list ranks, and ! to exit program");
        //Accepts user choice and loops while user choice is not "!"
        while(!userInput.equals("!")) 
            System.out.print(">> ");
            userInput = in.next();
            //if user choice is "!", the program stops
            if (userInput.equals("!")) 
                System.out.println("\nGood Bye :)");
            
            //if user choice is "?", the program stops
            else if(userInput.equals("?")) 
                //calls printRanks() method from StoryRanker to display file name and word count
                StoryRanker.printRanks();
            
            //Otherwise it's a file name
            else 
                //Uses default constructor to pass the file name to Story class
                Story myStory = new Story(userInput);
                //if getWordCount method from Story is greater than 0, call addStory() method from StoryRanker and pass the object
                if(myStory.getWordCount()>0) 
                    StoryRanker.addStory(myStory);
                
            
            
        

Story.java:

public class Story 
        //stores word count
        int wordCount;
        //stores file name
        String title;
        //Scanner class object for reading file
        Scanner fileRead;
        //file object
        File file;
        
        //Constructor for receiving file name
        Story(String fileName)
            //initializes file object by file name
            file = new File(fileName);
            //extracts file extension
            title = fileExtension(fileName);
        
        
        //Method that returns number of words in the file
        int getWordCount() 
            //try block
            try 
                //file is read
                fileRead = new Scanner(file);
                //Checks for data
                while(fileRead.hasNextLine()) 
                    //Word is read
                    fileRead.next();
                    //wordCount increases
                    wordCount++;
                
                //File is closed
                fileRead.close();
            
            //Catch for FileNotFoundException
            catch (FileNotFoundException e) 
                System.out.println("File Not Found");
            
            //returns wordCount
        return wordCount;
        
        
        //method that returns file name from complete file name with extension
        static String fileExtension(String str) 
            //null case
            if(str == null) 
                return null;
            
            //gets position of last "."
            int pos = str.lastIndexOf(".");
            //if there's no "." return the string as it is
            if(pos == -1) 
                return str;
            
            //returns string up to "."
            return str.substring(0,pos);
        

和 StoryRanker.java:

class Data 
    //Stores file name
    String fileName;
    //stores word count
    int wordCount;
    

class MyNewStack
    //stores 100 file names and word count
    Data myData[] = new Data[100];
    //points to top
    int top;
    //stores length
    int length;
    
    //default constructor
    void MyNewStack() 
    top = -1;
    length = 0;
    
    
    //Returns false if top = -1, but otherwise returns true
    boolean isEmpty() 
        if(top == -1) 
            return false;
            
        else 
            return true;
            
        
    
    //method pushes object to stack
    void push (Data d) 
        //Checks is stack is full
        if (top == 99) 
            System.out.println("Stack is full");
        
        //if stack isn't full
        else 
            //increases top position of stack by one
            ++top;
            //instantiates the array top index position
            myData[top] = new Data();
            //Stores file name and word count
            myData[top].fileName = d.fileName;
            myData[top].wordCount = d.wordCount;
            //increases length by one
            length++;
            
        
        
    //method to pop the stack top position
    Data pop() 
        //if stack top is less than zero, the stack is empty
        if(top<0) 
            System.out.println("Stack Underflow.");
            return null;
        
        //Otherwise, decrease length by one and return stack top position object
        else 
            length--;
            return myData[top--];
        
    
    
    //method to return stack a position
    Data peek(int a) 
        //if stack top is less than zero, the stack is empty
        if(top < 0) 
            System.out.println("Stack underflow.");
            return null;
        
        //otherwise returns stack a position object
        else 
            return myData[a];
        
    


//establish StoryRanker public class
public class StoryRanker 
    
    //MyNewStack class objects
    static MyNewStack stack1 = new MyNewStack();
    static MyNewStack stack2 = new MyNewStack();
    
    //Data class object
    static Data d = new Data();
    
    //Method to add file name and word count to stack
    public static void addStory(Story myStory) 
        //Extract data from myStory and store it in Data object
        d.fileName = myStory.title;
        d.wordCount = myStory.wordCount;
        //checks if stack is not empty
        if(!stack1.isEmpty()) 
            //Push object to first stack
            stack1.push(d);
        
        else 
            //loops until first stack top position
            for(int a = 0; a <= stack1.top; a++) 
                //if stack word count is less than current file word count
                if(stack1.peek(a).wordCount < myStory.wordCount) 
                    //Push object to second stack
                    stack2.push(stack1.pop());
                
            
            //puush current object to first stack
            stack1.push(d);
            //for loop until second stack top position
            for(int a = 0; a < stack2.length; a++) 
                //extracts second stack object and pushes it to first stack
                stack1.push(stack2.pop());
            
        
    
    
    //Method to display first stack contents
    public static void printRanks() 
        //loops until first stack top position
        for(int a = 0; a <= stack1.top; a++) 
            System.out.println((a+1)+ ": " + stack1.peek(a).fileName + ", size = " + stack1.peek(a).wordCount);
        
    
    

这是运行程序时的样子:

Write a file name to include your ranks, '?' to list ranks, and ! to exit program
>>the_boy_who_lived.txt
>>?

1: the_boy_who_lived, size= 392.

>>dracula_chapter1.txt
>>?

1: dracula_chapter1, size= 1309.
2: the_boy_who_lived, size= 392.

>>!

Good Bye :)

我遇到的问题是,每当我输入我正在使用的文件之一时,它都会不断返回“找不到文件”。我尝试输入整个地址,包括末尾的 .txt,但似乎没有任何进展。有没有人可以帮助我?

【问题讨论】:

只是文件名的路径是“相对路径”——操作系统在当前程序的工作目录中查找文件。因此,如果您只想输入文件名,则需要确保它与您启动程序时所在的目录相同。 【参考方案1】:
Story(String fileName)
    //initializes file object by file name
    String directory = "C:\\Users\\stlp\\IdeaProjects\\StoryCount\\src.\\" + fileName + ".txt";
    file = new File(directory);
    //extracts file extension
    title = fileExtension(fileName);

将目录的第一个字符串替换为您的实际绝对目录。确保包括双斜杠。输入文件名时,只需输入名称即可,因为 .txt 已附加。

【讨论】:

这绝对有帮助。唯一的问题是现在我遇到了一个问题,它不允许我加载我用于该程序的四个文本文件中的两个。 你能澄清一下你的文本文件目录是什么样的吗? C:\\Users\\myname\\eclipse-workspace\\program\\src\\excerpt_from_the_winds_of_winter.txt 您是否仍然收到未找到文件的异常或其他错误?

以上是关于加载文本文档并根据重复单词的数量对它们进行排名的 Java 程序 - 不断获取文件未找到错误的主要内容,如果未能解决你的问题,请参考以下文章

《C++》 猜单词小游戏

使用学习对文本文档进行排名?

使用随机森林对文本文档进行分类

基于距离矩阵的词聚类

词频统计设计

增加对每个学生的分数进行排名的功能