开发者

problem with the variables scope

// Calculating term frequency
    System.out.println("Please enter the required word  :");
    Scanner scan = new Scanner(System.in);
    String word = scan.nextLine();

    String[] array = word.split(" ");
    int filename = 11;
    String[] fileName = new String[filename];
    int a = 0;



    for (a = 0; a < filename; a++) {

        try {
            System.out.println("The word inputted is " + word);
            File file = new File(
                    "C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + a
                            + ".txt");
            System.out.printl开发者_C百科n(" _________________");

            System.out.print("| File = abc" + a + ".txt | \t\t \n");

            for (int i = 0; i < array.length; i++) {

                int totalCount = 0;
                int wordCount = 0;

                Scanner s = new Scanner(file);
                {
                    while (s.hasNext()) {
                        totalCount++;
                        if (s.next().equals(array[i]))
                            wordCount++;

                    }

                    System.out.print(array[i] + " ---> Word count =  "
                            + "\t\t " + "|" + wordCount + "|");
                    System.out.print("  Total count = " + "\t\t " + "|"
                            + totalCount + "|");
                    System.out.printf("  Term Frequency =  | %8.4f |",
                            (double) wordCount / totalCount);

                    System.out.println("\t ");

                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("File is not found");

        }

    }

This is my code to calculate the word count, total words and the term frequency of a text file containing text. The problem is i need to access the variable wordcount and totalcount outside of the for loop. But changing the place to declare the variable wordcount and totalcount changes the results too making it not accurate. Can someone help me on the variables so that i can get accurate results and also access the variables outside of the for loop ?


Simply declare them outside the loop, but keep assigning them to 0 inside the loop:

            int totalCount;
            int wordCount;
            for ( ... ) {                
              totalCount = 0;
              wordCount = 0;
              ...
            }
            // some code which uses totalCount and wordCount
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜