变量范围的问题

时间:2011-03-11 17:15:03

标签: java

// 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.println(" _________________");

            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");

        }

    }

这是我的代码,用于计算包含文本的文本文件的字数,总字数和术语频率。问题是我需要访问for循环之外的变量wordcount和totalcount。但更改声明变量wordcount和totalcount的位置会改变结果,使其不准确。有人可以帮助我改变变量,以便我可以获得准确的结果并访问for循环之外的变量吗?

1 个答案:

答案 0 :(得分:1)

只需在循环外声明它们,但在循环内继续将它们指定为0:

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