Java编程作业

Bir*_*ute 0 java

任务是:编写java程序,查找词性在词性之间分配的百分比.文本在文件中duomenys.txt.单词标记为:名词 - D,形容词 - B,动词 - V和介词 - 单词结尾的P.例如,"房子很大".标记的句子:the houseD isV bigB.这就是我所拥有的,第29-32行和第40行都有错误.

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Main {

    private static FileReader FileReader(File file) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    int[] frequencies = new int[ 4 ];
    private static int NOUN = 0;
    private static int ADJ = 1;
    private static int VERB = 2;
    private static int PREP = 3;

    public static void main ( String [] args ) throws IOException {
        String filename = "duomenys.txt";
        File file = new File( System.getProperty( "user.dir" ), filename);
        FileReader fin = FileReader( file );
        Scanner sc = new Scanner( fin );

        int wordCount = 0;

        while( sc.hasNext() ) {
            String s = sc.nextLine();
            String[] words = s.split(" ");
            for( int i = 0; i < words.length; i++) {
                frequencies[ NOUN ] += words[ i ].endsWith( "D" ) ? 1 : 0;
                frequencies[ ADJ ] += words[ i ].endsWith( "B" ) ? 1 : 0;
                frequencies[ NOUN ] += words[ i ].endsWith( "V" ) ? 1 : 0;
                frequencies[ PREP ] += words[ i ].endsWith( "P" ) ? 1 : 0;
                wordCount++;
            }
        }
        fin.close();
        String[] partsOfSpeech = {"nouns", "adjectives", "verbs", "prepositions"};

        for( int i = 0; i < partsOfSpeech.length; i++) {
            double percentage = frequencies[i] / wordCount;
            System.out.println( "There are " + frequencies[ i ] + " " + partsOfSpeech[ i ] + " (" + percentage + ")");
        }
    }
Run Code Online (Sandbox Code Playgroud)

第一个错误在这里: frequencies[ NOUN ] += words[ i ].endsWith( "D" ) ? 1 : 0;

错误是: non-static variable frequencies cannot be referenced from a static context.

Tim*_*sen 5

您正尝试在静态方法中访问某些非静态属性:

如果您有以下课程

public class Test{
 public int Property;

 public static voidDoSomething(){
  //You cannot access Property here, because
  //it's not static. It needs to be initialized first. 
 }

}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您有静态方法main,并尝试访问非静态方法frequencies.

为了避免这些问题,家庭作业练习通常会做这样的事情:

public class Main{
 public int Property;
 public void Start(){
  ///you can access Property here
 }

 public static void main ( String [] args ){
   new Main().Start();
 }
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以避免在试图访问你的属性时遇到的问题 static void main