Editor does not contain a main type eclipse ошибка

Just going through the sample Scala code on Scala website, but encountered an annoying error when trying to run it.

Here’s the code: http://www.scala-lang.org/node/45. On running it on Eclipse, I got this message ‘Editor does not contain a main type’ that prevents it from running.

Is there anything I need to do…i.e break that file into multiple files, or what?

asked Jul 11, 2009 at 13:32

Helen Neely's user avatar

Helen NeelyHelen Neely

4,6468 gold badges39 silver badges64 bronze badges

0

In Eclipse, make sure you add your source folder in the project properties -> java build path -> source. Otherwise, the main() function may not be included in your project.

answered Mar 28, 2011 at 20:34

milkplus's user avatar

milkplusmilkplus

32.7k7 gold badges30 silver badges31 bronze badges

2

I have this problem a lot with Eclipse and Scala. It helps if you clean your workspace and rebuild your Project.

Sometimes Eclipse doesn’t recognize correctly which files it has to recompile :(

Edit:
The Code runs fine in Eclipse

OpiesDad's user avatar

OpiesDad

3,3752 gold badges16 silver badges31 bronze badges

answered Jul 11, 2009 at 15:04

nuriaion's user avatar

nuriaionnuriaion

2,6212 gold badges23 silver badges18 bronze badges

4

A simpler way is to close the project and reopen it.

z3p5e6's user avatar

answered Jul 22, 2010 at 22:43

static's user avatar

staticstatic

3113 silver badges2 bronze badges

1

You have to make sure that your .java files are in the .src folder in eclipse. I had the same exact problem until I got it figured out.

answered Feb 29, 2012 at 14:40

ultra99's user avatar

ultra99ultra99

4131 gold badge7 silver badges11 bronze badges

0

Just make sure that the folder you work in is added to the built path:

right-click your folder —> build Path —> Use as source Folder

and it should now find main therein.

Sandra Rossi's user avatar

Sandra Rossi

11.7k4 gold badges22 silver badges47 bronze badges

answered May 16, 2013 at 13:56

kholofelo Maloma's user avatar

kholofelo Malomakholofelo Maloma

9533 gold badges15 silver badges26 bronze badges

1

You can try to run the main function from the outline side bar of eclipse.

solution

Community's user avatar

answered Apr 1, 2015 at 20:15

Fei's user avatar

FeiFei

5916 silver badges7 bronze badges

1

I had the same problem. I tried all sorts of things. And I came to know that

  1. My .java files were not linked and
  2. they were not placed in the ‘src’ folder.

Things I did:

Project properties >> Java Build Path >> Source

  • Deleted the original ‘src’ folder which was empty using ‘Remove’ option
  • Added the source that contained my source .java files using the ‘Add Folder’ option

This solved the error.

Torsten's user avatar

Torsten

1,6662 gold badges21 silver badges42 bronze badges

answered Jun 12, 2014 at 4:12

Anand Dhole's user avatar

0

Just close and reopen your project in Eclipse. Sometime there are linkage problems. This solved my problem

General Grievance's user avatar

answered Feb 26, 2016 at 8:12

Mohit Singh's user avatar

Mohit SinghMohit Singh

5,9492 gold badges24 silver badges25 bronze badges

0

A quick solution:

First, exclude the package:
Right click on the source package >> Build Path >> Exclude

Then include it back:
Right click on the source package >> Build Path >> Include

answered Feb 20, 2011 at 14:27

rwc's user avatar

What you should do is, create a Java Project, but make sure you put this file in the package file of that project, otherwise you’ll encounter same error.

enter image description here

shanethehat's user avatar

shanethehat

15.4k11 gold badges57 silver badges87 bronze badges

answered Feb 9, 2011 at 22:15

AbsintheSyringe's user avatar

That code is valid. Have you tried to compile it by hand using scalac? Also, have you called your file «addressbook», all lowercase, like the name of the object?

Also, I found that Eclipse, for some reason, set the main class to be «.addressbook» instead of «addressbook».

answered Jul 11, 2009 at 14:39

Daniel C. Sobral's user avatar

Daniel C. SobralDaniel C. Sobral

295k86 gold badges500 silver badges680 bronze badges

1

you should create your file by

selecting on right side you will find your file name,

under that will find src folder their you right click select —>class option

their your file should be created

agf's user avatar

agf

170k44 gold badges287 silver badges237 bronze badges

answered Aug 11, 2011 at 11:48

vijaya's user avatar

Make sure that your .java file is present either in the str package, or in some other package. If the java file with the main function is outside all packages, this error is thrown.

answered Jul 1, 2014 at 8:46

Sahil Pruthi's user avatar

0

Have faced the similar issue, resolved this by right clicking on the main method in the outline view and run as Java application.

answered Nov 10, 2017 at 6:27

Naresh's user avatar

0

I just had this problem too. The solution is to make sure eclipse created the project as Java project. Just create a new Java project and copy your class into the src folder (and import the eventual dependencies). This should fix the problem.

answered Apr 15, 2010 at 7:54

KullDox's user avatar

KullDoxKullDox

3531 gold badge3 silver badges11 bronze badges

1

The correct answer is: the Scala library needs to before the JRE library in the buildpath.

Go to Java Buildpath > Order and Export and move Scala library to the top

answered Feb 23, 2011 at 4:22

MGM's user avatar

I had this problem with a Java project that I imported from the file system (under Eclipse Helios). Here’s a hint: the src code didn’t seem to be compiled at all, as no «bin» directory showed up.

I had to create a Java project from scratch (using the wizard), then compare the .project files of the non-working and working projects.

The project giving «Editor does not contain a main type» had this as the «buildSpec» in the .project file:

<buildSpec>
</buildSpec>

But the working project had this as the «buildSpec»:

<buildSpec>
    <buildCommand>
        <name>org.eclipse.jdt.core.javabuilder</name>
        <arguments>
        </arguments>
    </buildCommand>
</buildSpec>

I copied this in, and the imported project worked.

I know my answer is for Java, but the same might be the issue for your Scala project.

answered Mar 12, 2014 at 0:28

user2704136's user avatar

May be the file you have created is outside the src(source) folder. Trying to call the class object(from the file located in the src folder) from the .java file outside the source folder results in the same error. Copy .java file to the source folder, then build it. The error will be gone.

answered Mar 21, 2014 at 6:52

Vamsi Tallapudi's user avatar

Vamsi TallapudiVamsi Tallapudi

3,5931 gold badge14 silver badges23 bronze badges

I had the same problem. I had the main class out of the src package, in other folder. I move it in and correct folder and solved

answered Aug 5, 2015 at 16:08

jacruz's user avatar

run «eclipse -clean -refresh» from command line. This fixed the issue for me when all other solutions failed.

answered Feb 12, 2016 at 1:19

MikeG's user avatar

MikeGMikeG

111 bronze badge

This could be the issue with the Java Build path.
Try below steps :

  1. Go to project properties
  2. Go to java Build Path
  3. Go to Source tab and add project’s src folder

This should resolve the issue.

answered Jan 4, 2017 at 14:09

AalekhG's user avatar

AalekhGAalekhG

3613 silver badges8 bronze badges

If it is maven project please check the java file is created under src/main/java

If you are not getting please change the JRE path and create the java files in above folder structure

answered Apr 26, 2017 at 13:06

ssomu's user avatar

ssomussomu

797 bronze badges

For me, in Eclipse 3.6, this problem occurs when my main method is not public. I caused the problem by having a main method like this:

static void main(String[] args) 

The dubugger was unable to detect this by itself. I am pretty suprised Eclipse overlooked this.

answered Jun 21, 2011 at 3:28

djangofan's user avatar

djangofandjangofan

28.3k61 gold badges196 silver badges288 bronze badges

In the worst case — create the project once again with all the imports from the beginning. In my case none of the other options worked. This type of error hints that there is an error in the project settings. I once managed to solve it, but once further developments were done, the error came back. Recreating everything from the beginning helped me understand and optimize some links, and now I am confident it works correctly.

answered Jun 20, 2012 at 8:19

Sergiu's user avatar

SergiuSergiu

3494 silver badges8 bronze badges

Follow the below steps:

  1. Backup all your .java files to some other location
  2. delete entire java project
  3. Create new java project by right click on root & click new
  4. restore all the files to new location !!

Unni Kris's user avatar

Unni Kris

3,0714 gold badges34 silver badges57 bronze badges

answered Jan 23, 2012 at 15:57

Mani Kandan's user avatar

File >> Import >> Existing Projects into Workspace >> Select Archive Filed >> Browse and locate file >> Finish. If its already imported some other way delete it and try it that way. I was having the same problem until i tried that.

answered Apr 4, 2013 at 0:52

Mike's user avatar

One more thing to check: make sure that your source file contains the correct package declaration corresponding to the subdirectory it’s in. The error mentioned by the OP can be seen when trying to run a «main type» declared in a file in a subdirectory but missing the package statement.

answered Nov 28, 2013 at 22:45

Daniel Ashton's user avatar

I have this problem too after I changed the source folder. The solution that worked for is just editing the file and save it.

answered Aug 24, 2014 at 10:32

Hunsu's user avatar

HunsuHunsu

3,2817 gold badges29 silver badges64 bronze badges

Try ‘Update Project’. Once I did this, The Run as Java Application option appeared.

answered Oct 25, 2015 at 20:56

George Santhosh's user avatar

In my particular ‘Hello World’ case the cause for this problem was the fact, that my main() method was inside the Scala class.

I put the main() method under the Scala object and the error disappeared.

That is because Scala object in Java terms is the entity with only static members and methods inside.

That is why Java’s public static void main() in Scala must be placed under object.

(Scala class may not contain static’s inside)

answered Jan 28, 2016 at 20:46

Vlad.Bachurin's user avatar

Vlad.BachurinVlad.Bachurin

1,3401 gold badge14 silver badges22 bronze badges

So in this tutorial, We will know that what kind of reasons can be for getting this error “Editor does not contain a main type” and we will see how to fix this error.

Basically, this type of Error means your Editor is not able to find the “main” method in any of your current program classes. The editor shows this error because when you want to run the project, at that time, the interpreter couldn’t find the main function to start the execution of the program.

Reasons for Error

So there can be various reasons causing this error:

  • If you have not declared the main method in your program, at that time it will be compiled successfully but while running the program, it will throw this error.
  • It can occur if the .java file has not linked or has not placed in the src
  • If you have not added a build path in the same folder where you are working.
  • If .class file or project file is not present in your workspace at that time it will occur.
  • If you are using Eclipse for java Programming and you have not declared the main method as public.
  • If the program is not compiled correctly.

Solutions

  • First, you should check that you have declared the “main” method in your program or not if you have not then you should write the “main” method inside your class.
  • If you are using eclipse and you have declared the “main” method in your program and you have written it inside the class then you have to check that you have added the build path or not. If you have not added then:- go to project properties -> Choose java build path -> Click on the source.
  • If the editor is not able to find the Source folder then you have to follow these steps:-
    1. Right-click on Project folder and go through the Properties
    2. Choose ‘Java Build Path’.
    3. Click on the ‘Sources’ tab on top.
    4. Click on ‘Add Folder’ on the right panel.
    5. Select your folders and apply them.
  • If you have not to clean your project then you should try this, Project -> Clean, or you can follow these steps on the command line -> run “eclipse -clean  -refresh.
  • In the last, confirm that you have declared the main method with “public” access specifier, like ->

public static void main(String[] args)

{

//body

}

  • And if you are sure about this that you have written the main method and code correctly then delete the current program file after copying your code and create a new file and paste in it.
  • Please Check that .class file is present in your workspace or not, If there is not present that file then you should add that file by compiling it before running the Project.
  • Wherever you have written the “main” method, you should sure about this that It is present inside the src folder, if It’s not then you have to place the “main” method inside the src folder and after that, you could simply run the Program.
  • If the program is not compiled correctly that time project does not contain an executable main class, So that time you have to compile the program correctly.

That was all about the reasons and solutions to this “Editor does not contain a main type”. If you have any queries or suggestions please leave in the comment below. We would love to help.

Я загрузил eclipse-jee-kepler-SR1-linux-gtk-x86_64.tar.gz. Это затмение встроено с java, а мой Lubuntu — 64-битный. Всякий раз, когда я компилирую и запускаю простой код в java, как показано ниже:

public class Sample{

   public static void main(String[] args){
       System.out.println("YOLO");
   }
}

Я всегда получаю Editor does not contain a main type.
Я помещаю файл в папку проекта с именем Sample. Это затмение должно скомпилировать java-код, потому что его дистрибутив IDE специализируется на java.

Как я могу решить эту ошибку?

Любая помощь будет высоко оценена.

Здесь моя структура проекта:
Изображение 41694

09 июнь 2014, в 12:08

Поделиться

Источник

15 ответов

Я подозреваю, что проблема заключается в том, что Sample.java должен находиться в пакете внутри папки src.

Я думаю, что затмение не будет автоматически смотреть за пределы.

phil_20686
09 июнь 2014, в 11:29

Поделиться

У меня была такая же проблема. Это будет звучать безумно, но если кто-то увидит это, попробуйте это до решительных мер. удалить подпись метода:

public static void main(String args[])

(Не является телом объявления основного простого метода)

Сохраните проект, а затем повторно напишите заголовок метода обратно на его соответствующий корпус. Сохраните снова и снова запустите. Это сработало для меня, но если он не работает, попробуйте еще раз, но очистите проект прямо перед повторным запуском.

Я не знаю, как это исправлено, но это произошло. Стоит ли задуматься, прежде чем воссоздать весь проект?

ThatOneGuy
23 март 2015, в 07:15

Поделиться

Проблема в том, что ваша папка не идентифицирована как папка источника.

  1. Щелкните правой кнопкой мыши папку проекта → Свойства
  2. Выберите «Java Build Path»
  3. Нажмите на вкладку «Источники» вверху
  4. Нажмите «Добавить папку» на правой панели
  5. Выберите свои папки и примените

Ramraj
29 апр. 2018, в 14:34

Поделиться

Щелкните правой кнопкой мыши свой проект > Запустить как > Запустить конфигурацию… > Приложение Java (в левой боковой панели) — дважды щелкните по нему. Это создаст новую конфигурацию. нажмите кнопку поиска в разделе «Основной класс» и выберите из него свой основной класс.

Ninad Pingale
09 июнь 2014, в 10:18

Поделиться

Для меня запись classpath в файле .classpath не указывает на нужное место. После изменения его в <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/> исправлена проблема

Siva Srinivas
15 май 2018, в 18:58

Поделиться

Изображение 141080

Создать исходную папку в разделе Ресурсы Java
Изображение 141081

sarath
10 фев. 2015, в 11:13

Поделиться

Убедитесь, что вы выполняете как > Java-приложение.

Если нет, вы можете попробовать Project > Clean

Еще несколько вопросов, которые касаются этого, которые могут быть полезны,
Обратитесь к этому вопросу

Cyrex
09 июнь 2014, в 10:20

Поделиться

Сначала найдите основной метод или нет. Если он есть, перезапустите свое затмение и щелкните правой кнопкой мыши на странице с основным методом. Перейдите в качестве приложения Java.

Sudhir Gaurav
13 июнь 2018, в 20:56

Поделиться

Щелкните правой кнопкой мыши на своем проекте, выберите «Создать» → «Исходная папка»

Введите имя src as Folder, затем нажмите «Готово».

Затем Eclipse распознает папку src как содержащую Java-код, и вы должны иметь возможность настроить конфигурацию прогона

Brendan Cody-Kenny
03 март 2018, в 22:18

Поделиться

Я установил Eclipse и создал проект Java.
Создал новый файл Java за пределами каталога src и попытался запустить его.
У меня такая же ошибка: «Редактор не содержит основного типа».
Я просто переместил java файл в папку src и мог просто запустить программу.
Я не мог понять, что другие ответы просят попробовать. Это было так просто.

Piyush Aggarwal
28 дек. 2017, в 12:02

Поделиться

Щелкните правой кнопкой мыши на файле Sample.java и удалите его. Теперь перейдите в File → New → Class, введите имя программы (например, hello), нажмите «Готово». Он создаст файл hello.java. Введите исходный код программы и окончательно нажмите ctrl + F11

Изображение 141082

Изображение 141083

Pavan Yogi
06 окт. 2017, в 06:05

Поделиться

У меня была такая же проблема. Я случайно удалил файл .classpath и .project в моей рабочей области. К счастью, это было в корзине, как только оно было восстановлено, проблем не было.

Pradeep AR
05 авг. 2017, в 23:15

Поделиться

В идеале исходный код должен находиться в пакете src/default, даже если вы не указали имя пакета. По какой-то причине исходный файл может находиться вне папки src. Создайте в папке scr, он будет работать!

Shiyas Cholamukhath
01 авг. 2017, в 07:47

Поделиться

поместите основной класс метода в папку src (в среде Eclipse).

Kranthi kiran
16 апр. 2018, в 10:15

Поделиться

Просто измените «String [] args» на «String args []».

Sonu Mishra
31 дек. 2017, в 09:23

Поделиться

Ещё вопросы

  • 0Как передать структуру функции в C ++
  • 1почему форма с именем добавляется в свойства документа
  • 0Как реализовать блокировку экрана для веб-страницы angularjs
  • 0Неправильный вывод при написании SQL-запроса с использованием функций Postgis
  • 1Это правильный способ издеваться над HttpContextBase, HttpRequestBase и HttpResponseBase для модульного тестирования файлов cookie?
  • 0HWIOauthBundle не перенаправляет на нужный путь после входа в систему
  • 1Android SetPixels () Объяснение и пример?
  • 0Скачать файл с URL как вложение
  • 1Циклы в Python: изменить один столбец на основе значений в других столбцах
  • 1Предложения по оптимизации этого Java-кода с помощью математических функций
  • 1Строки с одинаковым содержимым не равны?
  • 1Возврат списка файлов в Main Method для дальнейшей обработки файлов
  • 1Извлекать числа по позиции в Пандах?
  • 0CMAC: очень длинное целое число в качестве начального числа для функции random ()
  • 0JavaScript: список не обновляется после всплывающего поиска
  • 1Добавление объекта в список
  • 0условное форматирование по отрицательному значению
  • 0CakePHP генерирует ссылку, параметр аргумента которой определяется входом select
  • 1контраст с цветовой матрицей
  • 0как скопировать div в некоторый div и удалить оригинальный div
  • 1Увеличение идентификатора в корзине покупок
  • 1Проблема с фильтрацией данных Entity Framework по вычисляемым полям
  • 0Можете ли вы неявно вызвать метод, основанный на объекте
  • 1ASP.Net MVC длительный процесс
  • 0Как мне создать тесты для библиотеки, которую я создаю в C ++?
  • 0Зависание обоих элементов гнезда
  • 1Настройки парсера DOM, чтобы избежать атаки XML Injection
  • 0Как использовать Set with Group by в MySQL?
  • 0Воспроизведение видео HTML5 внутри рамки изображения iPhone
  • 0Поймать показ полосы прокрутки
  • 0Как сделать этот PHP, если оператор более простым и коротким?
  • 1Избегайте утечки памяти в клиенте c # неуправляемой DLL с утечкой памяти
  • 0Jquery переключения. Аналогичный пример
  • 1Включение «Прослушать это устройство» в Windows 7 через Java (и, возможно, Linux)
  • 1Глобальное сокет соединение
  • 1C # linq возможны рекомендации по множественному перечислению
  • 0Скользящая Div от левого угла к правому углу анимации
  • 0JQuery вызывает метод замены после загрузки метода
  • 1Найти корень производной абсолютного значения комплексного числа в симпы
  • 0Меню jQuery не скрывается при втором нажатии
  • 0Предупреждающее сообщение Недопустимый тип смещения от функции Где Mysql php
  • 1Java — библиотека черчения
  • 0JQuery Animate () выпуск
  • 0«Не найдено результатов» Список категорий JqueryUI
  • 1ListView Windows 8, можем ли мы изменить поведение Swipe влево / вправо на Swipe Up / Down
  • 1Связать атрибут XML со свойством класса
  • 0Jquery не воспроизводит последовательность видео
  • 0Привязка src в embed не работает в chrome
  • 1Как обрабатывать расширяемые ViewHolders в RecyclerView?
  • 0Выходной каталог MSBuild CL Task

Сообщество Overcoder

The problem statement “editor does not contain a main type” is usually encountered while coding on java. The error is encountered on the IDE Eclipse. Eclipse is an environment (IDE) used for writing programs in different languages. It mostly exists for writing programs in Java but can also be utilized for different languages such as c/c++ or even JavaScript with the help of extensions.

This article will provide guidance on why the “editor does not contain a main type” problem occurs while trying to run code in Eclipse. We will also find out what to do to fix these issues can be fixed.

Resolve issue statement “editor does not contain a main type”

There exist various reasons that can invoke the error. A few of the major reasons are elaborated on in this section.

Reason 1: Absence of the main method

The most obvious reason for this problem is that your code is missing the main function in the syntax of your existing class. This is the main function which is absent:

public static void main(String[]args)

Solution: Add the main method

The solution for the above-stated reason is quite straightforward. We simply need to implement the main function into our java class.

Below is an example of how we can implement the main function:

Reason 2: Build path

Another reason for this error revolves around the build path. When the build path is not set to the correct location where your java project exists, it can cause the “editor does not contain a main type” error. Usually, we want the build path to be set to the “src” folder. The “src” folder is the main source folder that is created alongside the project. It contains the program files and acts as the default build path.

Solution: Check the build path

The solution to the second reason is to fix the build path of your project. Follow these steps to fix your build path:

Step 1: Remove the build path

Expand your project file and right-click on the “src” folder. Here, you will find the “Build Path”, click on it and then navigate to the “Remove from Build Path”.

Step 2: Set the build path

After removing it, click on the “Build Path” again where you will find the option “Use as Source Folder”.

Reason 3: Check the build path of your Java package

Reason 3 is that the file that we want to run is not present in our src folder. The Java file we want to execute lies inside the “javatest” package and our build path is currently set to this package as can be seen in the following image. 

Solution: Add Java package to src folder

To add your Java package back to the “src” directory:

  • Right click on the package and ‘hover the mouse on the “Build path” option.
  • Click on the “Remove from Build Path

By doing so, your package will be moved to the “src” directory as shown below:

Conclusion

There are 3 major reasons that can cause the issue “editor does not contain a main type”. One is the missing main function which we learned to add to the java class. Another is the build path is not correctly set. This error can be fixed by refreshing the build path or checking the build path of your package file (where the java file is located). Here, you have learned multiple solutions to avoid the problem “editor does not contain a main type”.

Solution 1

Did you import the packages for the file reading stuff.

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

also here

cfiltering(numberOfUsers, numberOfMovies);

Are you trying to create an object or calling a method?

also another thing:

user_movie_matrix[userNo][movieNo]=rating;

you are assigning a value to a member of an instance as if it was a static variable
also remove the Th in

private int user_movie_matrix[][];Th

Hope this helps.

Solution 2

private int user_movie_matrix[][];Th. should be `private int user_movie_matrix[][];.

private int user_movie_matrix[][]; should be private static int user_movie_matrix[][];

cfiltering(numberOfUsers, numberOfMovies); should be new cfiltering(numberOfUsers, numberOfMovies);

Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.

Comments

  • I can’t seem to run the following code in Eclipse. I do have a main method and this is the currently opened file. I even tried the «Run As» option but I keep getting this error: «editor does not contain a main type». What am I doing wrong here?

     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());
            }
        }
    
    }
    

  • I’m trying to call the method that changes the dimensions of «user_movie_matrix» and «user_user_matrix»

  • I did not intend for user_movie_matrix to be a static variable. Does it have to be static for it to work properly?

  • It must be static as the code is written, because you directly access it from a static method, namely public static void main(String[] args).

  • oh i see…so what u should do is

  • oh i see…so what u should do is create a class method like’set_user_movie_matrix(x,y) {this.userNo = x; this.movieNo = y;}’` to change those values of an object …then instead of creating an object without a name do ‘cfiltering variable_name = new cfiltering(numberOfUsers, numberOfMovies);` and then using that variable call the methods like `variable_name.set_user_movie_matrix(userNo,movieNo)’

Recents

Related

Возможно, вам также будет интересно:

  • Edge код ошибки status access violation
  • Edeclaration ошибка загрузки библиотеки avlog4c dll
  • Edeclaration возникла ошибка просмотрите файл протокола
  • Edc ошибка шакман х3000
  • Edc ошибка на шакмане

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии