How to Start and Compile a Short Java Program in Eclipse
wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, volunteer authors worked to edit and improve it over time.
This article has been viewed 87,253 times.
These instructions will teach you how to start and compile a short Java program using the Indigo release of Eclipse. Eclipse is a free, open-source integrated development environment that you can use to develop Java programs, as well as programs in other languages. This tutorial assumes that you already have Eclipse installed on your computer. The purpose of this tutorial is to help you navigate Eclipse and to show off a few of its many features. Eclipse is easy to learn and will increase your productivity dramatically.
Begin by creating a new Java project. There are a few different ways of accomplishing this. You can click the arrow next to the left-most icon on the toolbar and select «Java Project» from the drop-down menu. Alternately, you can start a new Java project by choosing «File,» then «New,» followed by «Java Project.» You can also use the shortcut Alt+Shift+N.
Enter a project name. You will see a window titled «Create a Java Project.» The buttons «Next» and «Finish» at the bottom of the window will be greyed out until a project name is entered in the first field. To proceed, give your project a name and enter it into this field. For this tutorial, we will use the name «Project1.» Enter the name and then click «Finish.» Your new project will appear on the left-hand side of the screen under «Package Explorer» among existing projects. Projects are listed in alphabetical order.
Start a new Java class. Before you begin writing code, you will need to create a new Java class. A class is a blueprint for an object. It defines the data stored in the object as well as its actions. Create a class by clicking the «New Java Class» icon, which looks like a green circle with the letter «C» in the center of it.
Enter the name of your class. You will see a window titled «Java Class.» To proceed, enter the name of your class into the field «Name.» Since this class will be the main class of the simple project, check the selection box labeled «public static void main(String[] args)» to include the method stub. Afterwards, click «Finish.»
Enter your Java code. Your new class called Class1.java is created. It appears with the method stub «public static void main(String[] args)» along with some automatically generated comments. A method will contain a sequence of instructions to be executed by the program. A comment is a statement that is ignored by the compiler. Comments are used by programmers to document their code. Edit this file and insert the code for your Java program.
Watch out for errors in your code. Any errors will be underlined in red, and an icon with an «X» will show up on the left. Fix your errors. By mousing over an error icon, you can see a suggestion box that lists the ways you can fix the error. In this tutorial, we will double-click «Create local variable answer» so that the variable is declared first before it is used.
Ensure that your entire program is free of errors. There are three types of errors you must beware of: syntax errors, run-time errors, and logic errors. The compiler will alert you of the first of these three, the syntax errors. Examples of syntax errors are misspelled variable names or missing semi-colons. Until you remove all syntax errors from your code, your program will not compile. Unfortunately, the compiler will not catch run-time errors or logic errors. An example of a run-time error is trying to open a file that does not exist. An example of a logic error is opening and using data from the wrong file.
Compile your program. Now that your program is free from errors, click the triangular icon to run your program. Another way to run your program is to select «Run» from the main menu and then select «Run» again from the drop-down menu. The shortcut is Ctrl+F11.
Verify that the output is what you expected. When your program runs, the output, should there be any, will be displayed on console at the bottom of the screen. In this tutorial, our Java program added two integers together. As two plus two equals four, the program is running as intended.
Fix any run-time or logic errors. As stated previously, the compiler will only catch syntax errors. If the output of your program is different from what you’ve expected, then there might have been an error even though the program compiled. For example, if the output was zero instead of four, then there was a mistake in the program’s calculation.
Как выполнить / скомпилировать программу Java в IDE Eclipse
В этой статье мы расскажем, как скомпилировать программу в IDE Eclipse. Этот программный продукт распространяется свободно, а загрузить его можно по адресу http://eclipse.org. IDE Eclipse написана на языке Java, но ее переносимость ограничена из-за применения в ней нестандартной библиотеки управления окнами. Тем не менее существуют версии Eclipse для операционных систем Linux, Mac OS X, Solaris и Windows.
Существуют и другие IDE, но в настоящее время Eclipse распространена наиболее широко. Для того чтобы приступить к работе в этой IDE, выполните следующие действия.
- После запуска Eclipse выберите из меню команду File=>New Project ( Файл=> Создать проект ).
- Выберите вариант Java Project (Проект Java) в диалоговом окне мастера проектов (рис. 1). Здесь и далее показаны моментальные снимки экрана из пользовательского интерфейса версии Eclipse 2. В вашей версии Eclipse элементы пользовательского интерфейса могут несколько отличаться.
- Щелкните на кнопке Next (Далее), укажите в качестве имени проекта Welcome и введите полный путь к каталогу, содержащему файл Welcome, java (рис. 2).
- Щелкните на кнопке-переключателе Create project from existing source (Создать проект из существующего источника).
- Щелкните на кнопке Finish (Готово). В итоге будет создан новый проект.
Рис 1. Диалоговое окно Eclipse для создания нового проекта
Рис. 2. Настройка проекта в Eclipse
- Щелкните на треугольной кнопке рядом с именем нового проекта на левой панели, а затем на треугольной кнопке слева от варианта (default package), т.е. пакет по умолчанию. Дважды щелкните на имени Welcome .java. Появится окно с исходным кодом программы, как показано на рис. 3.
Рис. 3. Редактирование исходного кода в Eclipse
- Щелкните правой кнопкой мыши на имени проекта (Welcome) на левой панели. Выберите в открывшемся контекстном меню команду Run=>Run As=>Java Application ( Выполнить => Выполнить как =>Приложение Java ). В нижней части окна появится окно для вывода результатов выполнения программы.
Выявление ошибок компиляции
Рассматриваемая здесь программа состоит из нескольких строк кол и поэтому в ней вряд ли имеются ошибки или даже опечатки. Но для того, чтобы продемонстрировать порядок обработки ошибок, допустим, что в имени String вместо прописной буквы набрана строчная:
String[] greeting = new string[3];
Снова попытайтесь скомпилировать программу. Вы получите сообщение об ошибке, уведомляющее о том, что в коде программы использован неизвестный тип string (рис. 4). Просто щелкните на сообщении. Курсор автоматически перейдет на соответствующую строку кода в окне редактирования, где вы можете быстро исправить допущенную ошибку.
Рис. 4. Сообщение об ошибке, выводимое в Eclipse
Таким образом, на рассмотренном выше простом примере вы получили ясное представление о работе в IDE Eclipse.
Как создать исполняемый файл в Eclipse
wikiHow работает по принципу вики, а это значит, что многие наши статьи написаны несколькими авторами. При создании этой статьи над ее редактированием и улучшением работали авторы-волонтеры.
Количество просмотров этой статьи: 64 355.
После завершения проекта в Eclipse ваша следующая цель будет заключаться в создании исполняемой версии проекта. Наиболее простой и стандартный процесс запуска Java-проекта является запуск исполняемого файла (.EXE). В этом руководстве мы рассмотрим, как превратить типичный файл . jar в исполняемый файл!
Экспорт из Eclipse
Щелкните правой кнопкой мыши по проекту и нажмите кнопку «Refresh» (Обновить). Или же вы можете щелкнуть правой кнопкой и нажать F5 на клавиатуре. Это делается для того, чтобы весь ваш код находился в актуальном состоянии и не конфликтовал при попытке экспорта.
- Во-вторых, выберите «Export destination» (Место экспорта) с помощью кнопки «Browse. » (Обзор) или вручную, вводя месторасположение.
- Наконец, обеспечьте выбор переключателя «Extract required libraries into generated JAR»(Извлечь необходимые библиотеки в созданные JAR) «. Не волнуйтесь об остальной части меню. Нажмите кнопку «Finish» (Готово), когда будете довольны своим выбором.
Создание иконки
Найдите или создайте изображение, которое будет выглядеть уместным с вашей программой в виде значка. Помните, что иконка — это картинка, которую пользователь будет нажимать всякий раз, когда будут загружать программу; так что она будет видна часто! Попробуйте подобрать запоминающееся или наглядное изображение. Размер изображения должен быть 256×256 для того, чтобы можно было работать с ним должным образом как с иконкой.
Перейдите на сайт convertico.com. Это бесплатный сайт, который преобразует обычные файлы изображений (.png, .jpg) ) в удобный файл значка (.ico).
Или введите URL, или просмотрите файлы вашего компьютера, чтобы найти изображение, которое вы ранее выбрали. Нажмите кнопку “Go”.