string(175) "LC_CTYPE=C.UTF-8;LC_NUMERIC=en_US.utf8;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C" string(2) "S1" Objektorienteeritud programmeerimine (Narva Kolledž) - Kursused - Arvutiteaduse instituut
Arvutiteaduse instituut
  1. Kursused
  2. 2017/18 kevad
  3. Objektorienteeritud programmeerimine (Narva Kolledž) (P2NC.01.083)
EN
Logi sisse

Objektorienteeritud programmeerimine (Narva Kolledž) 2017/18 kevad

  • Home
  • Materials
  • Grading
  • Source Example
  • Links

In this session, we are going to use Notepad and Terminal.

1. Compile and run the program in the command line

When you start writing a piece of code in Java in any editor (e.g. Notepad, Gedit, etc.), the program looks like a simple text file. Unlike Python, the program cannot be executed at once. In Java, the program has to written, complied and after that executed.

1. Create a folder to keep the files (e.g., "c:\myProject", or "d:\myProject").

Do NOT save your works in Desktop or Documents as they are hard to locate. The directory name should not contain spaces or special characters.

2. Launch a programming text editor (e.g. NotePad, or NotePad++, or TextPad, DO NOT use MS Word) and enter the source code:

 /*
  * First Java program to say Hello
  */
 public class HelloWorld {   // Save as "HelloWorld.java" under "d:\myProject"
    public static void main(String[] args) {
      System.out.println("Hello, world!");
    }
 }

3. Save the file as HelloWorld.java into your folder (e.g. d:\myProject).

4. Start a cmd: click the "Start" button ⇒ "run..." ⇒ Enter "cmd").

5. Set the Current Drive to the drive where you have saved your source file HelloWorld.java. (e.g. if the source file is saved in drive d, enter d: as follow:

 C:> d:
 D:>

6. Set the Current Working Directory to the directory with the source file via the cd (Change Directory) command. (e.g. if the source file is saved into d:\myProject:

 D:> cd \myProject
 D:\myProject>

7. Issue a dir (List Directory) command to confirm that the source file is present in the current directory:

 D:\myProject> dir
 ......
 xx-xxx-xx  06:25 PM               277 HelloWorld.java
 ......

8. Invoke the JDK compiler javac to compile the source code HelloWorld.java.

D:\myProject> javac HelloWorld.java

The compilation is successful if the command prompt returns. Otherwise, error messages would be shown.

NB! If you have never compiled any java file on your computer, most probably the computer will throw out an error message like The name specified is not recognized as an internal or external command ... or Bad command or file name. This means that java cannot find the compiler. In such case show the path to the compiler , e.g.:
D:\myProject>path C:\Program Files\Java\jdk-9.0.4\bin
* If the previous remark has not helped you resolve the error, check Common JDK Installation Errors.

9. The output of the compilation is a Java class called HelloWorld.class. Issue a dir command again to check for the output.

 D:\myProject> dir
 ......
 xx-xxx-xx  01:53 PM               416 HelloWorld.class
 xx-xxx-xx  06:25 PM               277 HelloWorld.java
......

10. To run the program, invoke the Java Runtime java:

 D:\myProject> java HelloWorld
 Hello, world!

Conclusion: Computers do not directly understand Java. We need a compiler between the source code and the computer. When we are programming using the command line interface, the command javac HelloWorld.java will compile the HelloWorld.java file into bytecode, which can be executed using the Java interpreter. To run the compiled program, you can use the command java HelloWorld where HelloWorld is the name of the original source code file.

2. Change the first program

  1. Add one more statement System.out.println("Hello, World!") into the program.
  2. Change the output text.
  3. Compile the program in cmd and run it.
  4. Delete the last two characters ln in the first statement System.out.println. What has changed in the output?

3. Kitty

Write a program that prints a kitty speaking a greeting, similar to (but different from) the following:

 /\_/\     -----
( ‘ ’ )  / Hello, \
(  -  ) <  Junior  |
 | | |   \ Coder! / 
 (_|_)     -----

4. Loops

Write a program which calculates and outputs the sum of all the integers (inclusive) between 1 and 5. Solve the task using:

  • while loop
  • do ... while loop
  • for loop

Save each solution in a separate file.

5. Choose the loop

Choose an appropriate loop type for each task and write the program.

  1. Output integers from 1 to 5.
  2. Create 2 variables: sum and limit; then add value 2 to variable sum until sum becomes greater than limit.
  3. Output the following text using a loop: I like Java. The program has to print the message out at least once irrespectively of the loop conditions.

6. Input

Write a program that reads three edges for a triangle and determines whether the input is valid or not. (Hint: check the sum of the edges).

Example of the program output:

 Can edges 1, 2 and 10 form a triangle? False

Another example of the program output:

 Can edges 4, 5 and 6 form a triangle? True

7. Input with a loop

Write a program that reads an integer and checks whether it is even. The program must terminate if the user enters 0.

 Example of the program output:
 Is 25 an even number? False
 Is 100 an even number? True
 Is 0 an even number? I am done.

8. Kilos and Pounds

Write a program that displays the following table (note: 1 kg = 2.2 pounds; if you want to be more precise 1 kg = 2.20462262185 pounds). The output of the program should look like this:

 Kg        Pounds
 1         2.2 
 3         6.6
 ...
 197       433.4
 199       437.8

To output the result as a table, format the output. To create columns for the table use tab symbol \t. For example, System.out.println("abc"+"\t"+"def"); in such case string def will be allocated into a new column. To format floating point numbers, use System.out.printf. For example, System.out.printf("%.1f",1234.45) will display double numbers with one digit after the comma.

Upgrade the program so that the user is prompted for the range of the kilos (a starting value of the calculations, a step, an ending value of the calculation).

9. Sum of a series

Write a program that calculates and prints out the sum of the following series:

Upgrade the program so that the user is prompted for the number of the first terms to be summed.

10. A random number

Study the following example:

 double randomDouble = Math.random()*5+15;
 long roundedRandomLong = Math.round(Math.random()*5+15);
 int invalidInt = (int)Math.random()*5+15;

What is the output of the statements? What data type are the outputs?

Write a program that generates two random integers in the range of 21 and 90 (not inclusive), and prints out their fraction accurate to third decimal place.

After this session, we are going to use IntelliJ - a modern development environment which takes care of compiling the source code. When we choose to run the program, the development environment compiles and executes the program. Generally, all development environments compile source code while it is being written by the programmer, which means that simple errors will be noticed before executing the program.

  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused