2012-01-29 28 views
20

Parece que no puedo ejecutar el siguiente código en Eclipse. Tengo un método principal y este es el archivo actualmente abierto. Incluso probé la opción "Ejecutar como" pero sigo recibiendo este error: "el editor no contiene un tipo principal". ¿Qué estoy haciendo mal aquí?Error de Eclipse: "El editor no contiene un tipo principal"

public class cfiltering { 

    /** 
    * @param args 
    */ 

    //remember this is just a reference 
    //this is a 2d matrix i.e. user*movie 
    private static int user_movie_matrix[][]; 

    //remember this is just a reference 
    //this is a 2d matrix i.e. user*user and contains 
    //the similarity score for every pair of users. 
    private float user_user_matrix[][]; 


    public cfiltering() 
    { 
     //this is default constructor, which just creates the following: 
     //ofcourse you need to overload the constructor so that it takes in the dimensions 

     //this is 2d matrix of size 1*1 
     user_movie_matrix=new int[1][1]; 
     //this is 2d matrix of size 1*1 
     user_user_matrix=new float[1][1]; 
    } 

    public cfiltering(int height, int width) 
    { 
     user_movie_matrix=new int[height][width]; 
     user_user_matrix=new float[height][height]; 
    } 


    public static void main(String[] args) { 
     //1.0 this is where you open/read file 
     //2.0 read dimensions of number of users and number of movies 
     //3.0 create a 2d matrix i.e. user_movie_matrix with the above dimensions. 
     //4.0 you are welcome to overload constructors i.e. create new ones. 
     //5.0 create a function called calculate_similarity_score 
     //you are free to define the signature of the function 
     //The above function calculates similarity score for every pair of users 
     //6.0 create a new function that prints out the contents of user_user_matrix 

     try 
     { 
      //fileinputstream just reads in raw bytes. 
      FileInputStream fstream = new FileInputStream("inputfile.txt"); 

      //because fstream is just bytes, and what we really need is characters, we need 
      //to convert the bytes into characters. This is done by InputStreamReader. 
      BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
      int numberOfUsers=Integer.parseInt(br.readLine()); 
      int numberOfMovies=Integer.parseInt(br.readLine()); 

      //Now you have numberOfUsers and numberOfMovies to create your first object. 
      //this object will initialize the user_movie_matrix and user_user_matrix. 

      new cfiltering(numberOfUsers, numberOfMovies); 

      //this is a blankline being read 
      br.readLine(); 
      String row; 
      int userNo = 0; 
      while ((row = br.readLine()) != null) 
      { 
       //now lets read the matrix from the file 
       String allRatings[]=row.split(" "); 
       int movieNo = 0; 
       for (String singleRating:allRatings) 
       { 
        int rating=Integer.parseInt(singleRating); 
        //now you can start populating your user_movie_matrix 
        System.out.println(rating); 
        user_movie_matrix[userNo][movieNo]=rating; 
        ++ movieNo; 
       } 
       ++ userNo; 
      } 
     } 
     catch(Exception e) 
     { 
      System.out.print(e.getMessage()); 
     } 
    } 

} 
+3

¿Cuál es el nombre del archivo que contiene este código? – Zyerah

+0

cfiltering.java – JJJ

+1

Creo que esta es una pregunta perfectamente válida. De hecho, me encontré con esto y resolví mi problema: había creado una clase (erróneamente) en la carpeta fuente: src/main/test, y eclipse no podía manejar eso. Cuando lo creé correctamente bajo src/test/java, este error desapareció. – Jack

Respuesta

20

de cierre y reapertura Probar el archivo, a continuación, pulse Ctrl+F11.

Comprueba que el nombre del archivo que estás ejecutando es el mismo que el nombre del proyecto en el que estás trabajando, y que el nombre de la clase pública en ese archivo es el mismo que el del proyecto que eres trabajando también.

De lo contrario, reinicie Eclipse. ¡Avísame si esto resuelve el problema! De lo contrario, comente, y lo intentaré y lo ayudaré.

+0

Ahora que lo tengo funcionando en mi propio código, no recibo errores. ¿Intentas recrear el proyecto? – Zyerah

+1

Eso pareció haber hecho el truco, ¡gracias! – JJJ

+2

El reinicio me ayudó, si es de mi interés. – kiltek

3

¿Importó los paquetes para leer el archivo?

import java.io.BufferedReader; 
import java.io.FileInputStream; 
import java.io.InputStreamReader; 

también aquí

cfiltering(numberOfUsers, numberOfMovies); 

¿Estás tratando de crear un objeto o llamar a un método?

también otra cosa:

user_movie_matrix[userNo][movieNo]=rating; 

va a asignar un valor a un miembro de una instancia como si fuera una variable estática también eliminan la Th en

private int user_movie_matrix[][];Th 

Espero que esto ayude.

+0

Estoy tratando de llamar al método que cambia las dimensiones de "user_movie_matrix" y "user_user_matrix" – JJJ

+0

oh veo ... entonces lo que debes hacer es – bernabas

+0

oh ya veo ... así que lo que deberías hacer es crear una clase método like'set_user_movie_matrix (x, y) {this.userNo = x; this.movieNo = y;} ''para cambiar esos valores de un objeto ...entonces, en lugar de crear un objeto sin un nombre, 'cfiltering variable_name = new cfiltering (numberOfUsers, numberOfMovies);' y luego usar esa variable llamar a los métodos como 'variable_name.set_user_movie_matrix (userNo, movieNo) ' – bernabas

1

private int user_movie_matrix[][];Th. debe ser `private int user_movie_matrix[][];.

private int user_movie_matrix[][]; debería ser private static int user_movie_matrix[][];

cfiltering(numberOfUsers, numberOfMovies); debería ser new cfiltering(numberOfUsers, numberOfMovies);

Sea o no el código funciona como se esperaba después de estos cambios está más allá del alcance de esta respuesta; Hubo varios errores de sintaxis/alcance.

+0

No pretendía para user_movie_matrix ser una variable estática ¿Tiene que ser estático para que funcione correctamente? – JJJ

+0

Debe ser estático a medida que se escribe el código, porque ** directamente ** accede desde un método estático, a saber, 'public static void main (String [] args)'. –

Cuestiones relacionadas