Anda di halaman 1dari 14

Lab 1

DITP 3113 Object-Oriented Programming

Lab 1: Introduction to Java Programming

1.1 Objectives
By the end of this lab session, you should be able to: Know how to write and save simple Java program by using the Notepad. Know how to use MS DOS prompt to compile and execute the Java program. Apply the basic structure of Java programming. Getting started with IDEs.

1.2 Introduction
In this lab session, students will learn to write simple Java program by using some of the Java basic structures. This session will show them on how to compile and run the Java program by using MS DOS Prompt. All students will also learn to identify some errors and try to find their matching solutions.

1.3 Step-by-step
1.3.1 How to change the class path. You must first check if Java is installed in your machine. Look for the Java folder in the Program Files. Copy the complete path, for example: C:\Program

Files\Java\jdk1.6.0_20.

1 / 14

Lab 1

DITP 3113 Object-Oriented Programming

When installing the Java SDK, changing class path is important in order to allow you to be able to compile and run java programs. First, go to Start > Control Panel. Then, find the icon of System in the Control Panel. Double click it to open the System Properties. In the System Properties, click the Advanced tab. It will show the Environment Variables button. Click the button to display the Environment Variables of the system.

2 / 14

Lab 1

DITP 3113 Object-Oriented Programming

Look at the System Variables where it shows the Path Variable and its Value. Next, click onto the Path row and then click the Edit button. It will display another box where the changes can be made in there.

3 / 14

Lab 1

DITP 3113 Object-Oriented Programming

Below is the box to edit the Path Variable. The next step is to add the address of JDK in front of all other values which usually is just the same as shown below C:\Program Files\Java\jdk1.6.0_20\bin; (or the current jdk version). Always remember to put the semicolon (;) after the value is added. If not, the system wont recognize the new value.

Lastly, click OK to this Edit System Variable box and to all other boxes appear after this. Now, the Java program can be executed or run in any directory in the system.

4 / 14

Lab 1

DITP 3113 Object-Oriented Programming

1.3.2 How to use and save Java program in the Notepad. First, open Notepad. You can find it by going from Start > All Programs > Accessories > Notepad. You can just write or edit from it like other text editor. Type the Java code given below.

The next step is to save the file. Be careful when you are saving the file; make sure the file type is set to All File and the file name ends with .java (the dot notation is compulsory). Remember that Java differentiate the capital and small letter. Make sure that the name of the file is just the same as the class name in the program. In the example given above, the class name is Test so the file name should be Test.java.

1.3.3 How to compile and execute the Java program by using MS DOS Prompt. First, activate MS DOS Prompt. Go to Start > All Programs > Accessories > Command Prompt. Next, change the directory into the same directory where the file has been saved. For example if the file is in C:\ directory, type cd C:\ to change into C:\ directory.

5 / 14

Lab 1

DITP 3113 Object-Oriented Programming

To compile, use the javac command to start compiling. Make sure the file name is exactly the same because java applies case sensitive factor. For example, type javac Test.java to compile the file in the example above. If the code has no error, a .class file will be created. The next step is to execute the program by using java command. For example, type java Test to run the program. The output should be; DITP 3113 Object Oriented Programming!

6 / 14

Lab 1

DITP 3113 Object-Oriented Programming

1.3.4 List of error messages and its solutions. The first two errors shown in Table 1 below are compile-time errors (errors that happen when compiling a program). However, the third error is a run-time error (an error that happened when the Java interpreter tries to run or execute a program by using java filename command). Usually, the first row of the message explains about the error and the second row shows where it happens or any solution that should be done for the error. Sometimes the compiler cant give an exact description about the error. Every programmer is needed to look carefully at their programs to find the exact matching solution. Table 1: List of possible errors when compiling a Java program
Error: Test. Java: 3: ; expected System.out.println(DITP3113 Object Oriented Programming!)^

Description: The first row shows the file name at certain line of the program that creates the error and a simple description about the error. The second row shows the code of the program that might cause the error. A caret symbol (^) can be found referring to the error. Solution: Use Notepad to add semicolon (;) at the end of the line and then save the file to save the changes made. Error: Cubaan.java:1: class Test is public, should be declared in a file named Test.java public class Test {

Description: The file name doesnt match the class name given. Remember, the file name must be the same as the class name given after the keyword public class in the program. The file is needed to be saved in double quotation as for example Test.java. Solution: Type the correct file name when compiling by using javac command or use Notepad to change the file name saved. Error: Exception in thread main java.lang.NoClassDefFoundError: test (wrong name: Test)

Description: The file name typed is not the same as the .class file. Make sure that the file name is correct while using a java command. As for example java Test Solution: Type the correct file name when executing the java command.

7 / 14

Lab 1

DITP 3113 Object-Oriented Programming

Table 2 below lists some of the basic commands to be used in DOS. Table 2: Some basic commands in DOS
Command dir dir /p cd \ cd .. Description List out the directory. List out the directory part by part if the list is too long to be printed out in one screen (pauses). Change the current directory into the root directory in the same drive. Change the current directory into the former directory. Change the current directory into a certain sub directory. Your directory : Latihan java |_____ Makmal1 cd name of the directory Type cd Latihan java beside C:/> C:\> cd Latihan java The directory will change into Latihan java such as: C:\Latihan java> To go to Makmal1 directory, just type cd Makmal1 after this > C:\Latihan java>cd Makmal1 The output will be: C:\Latihan java\Makmal1> Change the current drive into any drive chosen. For example, type d: (It will change the current drive into drive d). This will cancel the execution of the program. This will show the last dos command that has been used.

drive: Press Ctrl+ C Press F3

To use the DOSKey program, just type doskey /insert in the command prompt. To use the DOSKey program in the future, type doskey /insert in the path statement. Keystroke Up and down arrow Left and right arrow Description It will show the current DOS command that has been typed recently. Use the cursor to edit text in the DOS prompt.

8 / 14

Lab 1

DITP 3113 Object-Oriented Programming

1.3.5 To receive input and print output The Java program prepare the facility for the programmer to reused the Java predefined packages and classes. To print output, the programmer can use java.io package while to receive input, they can use java.util package. One of the way to receive input is by using the Scanner class in java.util package that will allow the programmer to read from file, disk or keyboard. To print output, the program can use System.out command of print, println or printf method. Below is the example of a program that declares two variables and try to get the sum of both numbers. The value of both numbers are inserted by using keyboard. These are the steps to let the program to read input from keyboard. a. b. c. d. e. f. g. Import package java.util. Declare a class for the program. Write the main method. Create an object of class Scanner to able the program to read input. Declare the variable that is going to be used in the program. Read input. Print output.
// program uses class Scanner

import java.util.Scanner;

public class Addition { public static void main(String[] args) { // create Scanner to obtain input from command window Scanner input = new Scanner(System.in); int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 // read first number from user System.out.print("Enter first integer: "); number1 = input.nextInt(); // read second number from user System.out.print("Enter second integer: "); number2 = input.nextInt(); sum = number1 + number2; // sum up numbers

System.out.printf("Sum is %d\n, sum); } } 9 / 14

Lab 1

DITP 3113 Object-Oriented Programming

1.3.6 Simple GUI-based Input/Output with JOptionPane You can use JOptionPane to receive input and print output like we use the Scanner class. JOptionPane provide the GUI look and it is in the javax.swing package. Well look into the following example to understand how to use the JOptionPane.
//Jumlah.java //Mencampur 2 nombor nombor pertama dpd input pengguna // nombor kedua adalah pilihan dpd combo box import javax.swing.*; public class Jumlah { public static void main(String[] args) { int no1, no2=0; Object[] possibleValues = { 4, 3, 7 };

//Nilai pd combo box

//Terima input dpd JOptionPane melalui showInputDialog String pertama = JOptionPane.showInputDialog("Nombor pertama? "); //Terima input dpd pilihan berdasarkan nilai di combo box Object nilaiDipilih = JOptionPane.showInputDialog(null, "Nombor kedua?", "Input",JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]); //Tukar nilai string pd input ke integer no1 = Integer.parseInt(pertama); //Terima nilai combo box ke bentuk integer no2 = ((Integer)nilaiDipilih).intValue(); //Paparkan hasil melalui showMessageDialog JOptionPane.showMessageDialog(null, "Jumlah = " + (no1 + no2), "Jumlah 2 nombor",JOptionPane.PLAIN_MESSAGE); } }

1.3.7 Getting Started with IDEs Next, after getting familiarized yourself compiling and running Java program using the command prompt, you may want to start getting used with different Integrated Development Environment (IDEs) such as TextPad, JCreator, Eclipse, NetBeans, jGRASP or DrJava.

10 / 14

Lab 1

DITP 3113 Object-Oriented Programming

1.4
1.

Exercises
Type the program below and named it as TestOne.java. Compile and run the program. What kind of error that has been produced? Find the solution for the error.
public class Test1 { public static void main(String[] args) { System.out.println("Could you trace the error?"); } }

Solution: ________________________________________________________________________ ________________________________________________________________________ _______________________________________________________________ 2. Type the program below and named it as Test2.java. Compile and run the program. What kind of error that has been produced? Find the solution for the error.
public class Test2 { public static void main(String what) { System.out.println("Is there any error now?"); } }

Solution: ________________________________________________________________________ ________________________________________________________________________ _______________________________________________________________ 3. Type the program below and named it as Test3.java. Compile and run the program. What kind of error that has been produced? Find the solution for the error.
public class Test3 { public void main(String [] args) { System.out.println("What is the error this time?"); } }

11 / 14

Lab 1

DITP 3113 Object-Oriented Programming

Solution: ________________________________________________________________________ ________________________________________________________________________ _______________________________________________________________ 4. Type the program below. This is the example of a program that prints out a message in the command prompt. Name it as Welcome.java.
public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }

5.

Type the program below. This is the example of a program that prints out a message by using printf method. Name it as Welcome1.java. Find out the difference between this program and the program in number 4.
public class Welcome1 { public static void main(String[] args) { System.out.printf("%s\n%s\n", "Welcome to", "Java Programming!"); } }

Solution: ________________________________________________________________________ ________________________________________________________________________ _______________________________________________________________ 6. Type the program below. This is the example of a program that uses Swing and show the message by using a dialog box. Name it as WelcomeMessageBox.java. Can you differentiate the difference between this program and the program in number 4 & 5?
import javax.swing.JOptionPane; public class WelcomeMessageBox { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "Welcome to Java!", "Example 1.2 Output", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } 12 / 14

Lab 1

DITP 3113 Object-Oriented Programming

Solution: ________________________________________________________________________ ________________________________________________________________________ _______________________________________________________________ 7. Type the program below. This is the example of a program that use Swing and show the message by using a dialog box after inserting a string of name into the input dialog.
import javax.swing.*; public class Hello { public static void main(String[] args) { String name; //declares a variable called name name = JOptionPane.showInputDialog(null, "What is your name?"); JOptionPane.showMessageDialog(null, "Nice to meet you, " + name + "."); } }

8.

Type the program below. This is the example of a program that declares a variable and uses it to multiply the number with 2.
public class Number { public static void main(String[] args) { int num; // declares a variable called num num = 100; // assigns num with value 100 System.out.println("This is num: "+ num); num = num * 2; System.out.print("The value of num * 2 is "); System.out.println(num); } }

9.

Write an application that declares two integers and values them with any numbers chosen then print their sum, product, difference and quotient (division).

13 / 14

Lab 1

DITP 3113 Object-Oriented Programming

10. Write the program that converts Fahrenheit to Celsius. The formula for the conversion is as follows:
celsius = (5/9) * (fahrenheit 32)

Your program reads a Fahrenheit degree in double from the input dialog box, then converts it into Celsius and displays the result in a message dialog box. 11. Write a program that computes the volume of a cylinder. The program should read in radius and length, and compute volume using the following formulas:
area = radius * radius * pi volume = area * length

1.5
1. 2. 3. 4.

Self-Review Questions
All Java source code filenames must end with What is the command to compile a Java program? What is the command to run a Java application? What is wrong if the exception NoClassFoundError is raised when you run a program from the DOS prompt? .

5.

What is wrong if the exception NoSuchMethodError: main is raised when you run a program from the DOS prompt?

14 / 14

Anda mungkin juga menyukai