When I compile this code, it gives me an error that says it "cannot find symbol" for the variable count. Am I not returning it correctly? Or do I have to declare the variable in the main method, and not in the wordScore method?
import java.util.Scanner;
import java.io.File;
public class assignment3 {
public static void main (String []args){
Scanner input = new Scanner(System.in);
double totalCount = 0;
//ask user to enter a movie review line
System.out.println("Please enter a one line movie review ");
String oneLineMovieReview = input.nextLine();
//putting each word into a string array
String[] words = oneLineMovieReview.split(" ");
//calling the wordScore method to calculate word score for each word
for(int i = 0; i < words.length; i++){
wordScore(words[i]);
totalCount = totalCount + count;
}
}
public static double wordScore(String oneLineMovieReview) {
Scanner input = new Scanner(System.in);
double count = 0;
double sumScore = 0;
double average = 0;
int totalCount = 0;
File file = new File("movieReviews.txt");
try {
Scanner fInput = new Scanner(file);
while (fInput.hasNextLine()) {
String line = fInput.nextLine();
if (line.contains(oneLineMovieReview)){
count++;
sumScore += Integer.parseInt(line.substring(0,1));
}
}
System.out.println("The word " + oneLineMovieReview + " appears " +
count + " times.");
average = sumScore / count;
System.out.println("The average score is " + average);
System.out.println(totalCount);
System.out.println();
} catch(Exception e) { }
return count;
}
}
答案 0 :(得分:-1)
Here, you do
for(int i = 0; i < words.length; i++){
wordScore(words[i]);
totalCount = totalCount + count;
}
Now, count
isn't visible here as it was declared in the wordScore
method. I suppose you intended doing
for(int i = 0; i < words.length; i++){
totalCount = totalCount + wordScore(words[i]);
}
答案 1 :(得分:-1)
Both main
and woreScore
are static methods, meaning they share no state except for members of the class which are also static
. The main
method needs its own count
variable, keeping in mind this will be separate from the one in any other function. For main
and wordScore
to share the same value of count
, the variable will have to either be static
, or the functions extracted into a separate class and made non-static.
(Also, it's often best to keep the class which has the main
entry point separate from the class doing your program's actual work).