SSAI 2018Z: Class 1. Basics of Java programming. Page 1 of 6 Selected Sections of Applied Informatics LABORATORY 0 INTRODUCTION TO JAVA PROGRAMMING. BASIC LANGUAGE INSTRUCTIONS. CONSOLE APPLICATION. CONDITION, LOOP INSTRUCTIONS. PROGRAM ARGUMENTS. TABLIC
SSAI 2018Z: Class 1. Basics of Java programming. Page 2 of 6 I. Opening a new Java Application project in NetBeans IDE2 1. Open the NetBeans IDE environment by clicking the icon on the desktop.. 2. From the File menu, select New Project... or click the second button on the toolbar to the left.. 3. In the New Project window, select Java in the Categories: Java panel and in the Projects: Java Application panel and confirm with Next > button. 4. In the New Java Application window, fill in the dialog boxes as shown below (case sensitive): In the filed Project Name: type the name of the project Projekt1 In the filed Project Location: select the Z:\ folder as the destination of your project. Check the option: Create Main Class. Give the main project class named Projekt1 a name Klasa1 (instead of Main) by entering projekt1.klasa1 in the lower text field (projekt1 is the name of a Java class package); confirm with Finish button Remember the following generally accepted rules: name of the primary class must match the name of the file that stores its program, the class name must start with a letter and must not contain space characters, class names are usually written in capital letters. 5. In the Files window, view the structure and contents of the Netbeans project folders that were created for an empty Java Application in the Z folder: 6. Start an empty Java application with the F6 function key. After a successful compilation, a build folder will be created. In the Files window, look at its contents. Folder Projekt1\src\projekt1 already contains the source file of the project called Klasa1.java Folder build will be created after a successful compilation and will contain subfolders classes, and then project1, which will contain byte code of our application. Folder Projekt1\build\classes\projekt1 will contain a file named Klasa1.class II. The first program in Java 1. Type the following instructions into the Netbeans editor window public class Klasa1 { public static void main (String[] args) { System.out.println("Hallo in Java"); 2. Run the F11 project compilation and check for errors. 3. Run the program by pressing F6 and observe the results of the execution in the Output window. As a result, a welcome is displayed: Hallo in Java III. Arguments of the programme 1. Return to editing the source text of the program. Before the main() method's curly brackets close, declare two text variables a and b, and then assign to them the program arguments contained in two consecutive elements of the args array. The program's argument can be any character string that does not contain spaces. String a, b;
SSAI 2018Z: Class 1. Basics of Java programming. Page 3 of 6 a= args[0]; b= args[1]; 2. In the following instructions, display the values of the variables a and b: System.out.println(a); System.out.println(b); 3. Save your changes and restart the program. If you do not provide any argument, an execution error occurs, i.e. an exception, and the following message appears in the command window: Exception in thread "main" java.lang.arrayindexoutofboundsexception: denoting an attempt to refer to a non-existent element of the args array. Such an exceptional situation in the program should be predicted and handled, what we will do later in the exercise. 4. Define the arguments of the program. To do this, enter the Properties of the project using the pop-up menu. In the "Project Properties" dialog box, go to the [Run] tab. In the "Arguments" field, enter any integers separated by a space: 10 15. 5. Add an instruction displaying the sum of arguments a and b: System.out.print("Sum of arguments: "); System.out.println(a+b); then compile and run the program and analyse the result. IV. Display results in the Output window; constants and text variable 1. Delete the current content of the method main(). 2. Inside the main() method, type calling a method for displaying text: "Welcome to NetBeans". (If the line numbering is not displayed, you can select from the menu command View Show Line Numbers.) 3. If the instruction is incorrectly typed (e.g. case-insensitive), the following button will appear instead of the line number. Then point the mouse cursor over this button and a description of the error will appear in the explanation window. (Usually the beginning of the red toothed underline in a line indicates where the error occurred.) 4. At the end of the main() method, before the curly bracket that closes it, declare the String class object variable text and assign it a specific string (text string): String text = " The Java language was created by SUN. "; 5. In the next line add the instruction: System.out.println(text); 6. Start the program and check its operation.. V. Arguments and numeric variables; conversion of text to numbers; calculation of expressions and display of the result
SSAI 2018Z: Class 1. Basics of Java programming. Page 4 of 6 1. Return to program editing and continue to declare three variables k,m, n, type int, which will be used to store integers. Assign the k variable a constant value of 10. Assign the variables m and n to the first two arguments of the program using the parseint() conversion method of the Integer class.: int k = 10; int m = Integer.parseInt(args[0]); int n = Integer.parseInt(args[1]); 2. Run the program without arguments. Because no elements are passed to the args array on the command line, an execution error (exception) will occur, represented by the class ArrayIndexOutOfBoundsException (exceeding the range of array indices). 3. To prevent exceptions that may occur when displaying non-existent arguments, place the instructions in V.1 inside the part try of instructions try-catch: try{ int m = Integer.parseInt(args[0]); int n = Integer.parseInt(args[1]); System.out.println(m); System.out.println(n); catch (ArrayIndexOutOfBoundsException e) { System.out.println("No args"); (The program will try to display arguments in some modes, and in case of failure it will go to the catch part, which will intercept the exception of exceeding the range of the array and display a message.) 4. In the Projects window, right-click the name of the Project1 project. Then select Properties. In the Project Properties - Project1 window, in the Categories: panel, highlight the Run category. In the Arguments: field, type two integers separated by spaces as program arguments 5. Save changes and run the program. 6. Execute the program by providing text arguments instead of numeric ones. The given arguments cannot be converted to integers, which will result in an exception to the NumberFormatException class (incorrect format of the number). 7. Return to program edition. In the instruction try-catch add secont part: catch, which will handle exceptions to this class: catch (ArrayIndexOutOfBoundsException e) { System.out.println("No args"); catch (NumberFormatException e) { System.out.println("Incorrect argument! Enter two integers. "); 8. At the end of the try part, declare an integer variable named sum and assign the sum of three variables to it with the following instruction: int sum =k+ m + n; 9. In the next line add an instruction displaying the text "sum=" and the contents of the variable sum, the result of the summation: System.out.print("sum = "); System.out.println(sum); 10. Save the changes, compile the program and execute it with two integers separated by a space.. 11. Below the sum, display the product of the variables k, m. n - in order to do so, go to the edition of the program, complete it with the appropriate instructions.. 12. Check the operation of the program in case of correct and incorrect arguments. VI. Standard input/output: reading text from the keyboard and displaying in the Output window.t 1. In the NetBeans environment, create a new project using the File New Project menu command. In the New Project dialog box, select Java in the panel Categories: Java, and Java Application in the Projects panel. In the New Java Application window, give the project the name Projekt21 and the main class the name WeWy. As the destination of the project, select the working folder Z:\. At the beginning of the main() method, create a field representing a buffer reader that will read single lines of text from the keyboard BufferedReader we = new BufferedReader(new InputStreamReader(System.in)); 2. By command Fix Imports from the pop-up menu import BufferedReader and InputStreamReader classes from the java.io package of Java library resources. Import clauses will appear in the initial part of the program. In order to read the values of subsequent data from the keyboard, we will use the readline() of we object. Before reading the next data we will display a hint for the user. Below the reader's declaration add instructions: System.out.print("Your Name and Surname:"); String student = we.readline() ; Method readline()as an input/output operation may generate class execution errors (exceptions) IOException so a compilation error occurs: unreported exception java.io.ioexception; must be caught or declared to be thrown. Click on the error button and select Add throws clause for java.io.ioexception This will result addition to the header of the method main() frphrase throws IOException and transferring the handling of this error to the system.
SSAI 2018Z: Class 1. Basics of Java programming. Page 5 of 6 3. Start the program, then click to move the cursor to the Output window and enter your data, ending it with the ENTER key.. 4. Enter the album number and average note as the next data; these will be the values of two numeric variables - total and real.. int Index = Integer.parseInt(we.readLine()); float note = Float.parseFloat(we.readLine()); 5. Before each instruction to read the data, add an instruction that displays a hint for the user. 6. Add an instruction to display the entered data. Start the program. Observe the effect of incorrect entry of an album number or rating (e.g. letter instead of a number, comma instead of a dot). 7. To handle an exception generated by an erroneous entry, enclose the following instructi try-catch the instructions for converting text into numbers assigned to variables in point I.6 Index and note. In part catch recognize the class exception NumberFormatException and add an instruction that will display a message " incorrect number format". Check the operation of this exception. VII. Assignment instructions and data types. Data conversion. Arithmetic operations. Use of mathematical functions. 1. In the next example we will program calculations for numbers loaded from the keyboard. We make them in a new project, created as a copy of the project Projekt21. In the Projects window, right-click the Projekt21 name and select Copy from the popup menu. In the dialog box, enter the name of the new Project22 projectexpand the folders of a new project and change the name of the main class to Calculations, by clicking on the class name WeWy with the right mouse button and by selecting the following commands Refactor Rename. Double-click on the name of the Calculation class, open it in the NetBeans editor and modify it. 2. Delete the instruction to read the name and change the instruction displaying these data to the following (enter your data): System.out.println("Program author: xxxx yyyyyyyy"); 3. Change the instructions for reading the album number and rating to reading two integers (type int), modify the hints before reading each of the data: int a = Integer.parseInt(we.readLine()); int b = Integer.parseInt (we.readline()); 4. In the following lines display the sum, difference, product and quotient of numbers a and b: System.out.println("arithmetic operations on numbers " +a+ "and " +b); System.out.println("sum ="+ (a+b)); System.out.println("differential ="+ (a-b)); System.out.println("multiplication ="+a*b); System.out.println("quotient ="+a/b); 5. Where two integers are subdivided, provision must be made for the situation of subdivision by zero, which gives rise to a class exception. ArithmeticExceptionTo handle it, add after an existing phrase catch another phrase catch the character: catch(arithmeticexception e) {System.out.println("Calculation error!"); 6. Run the program and check its operation 7. Then change the type of variables a and b to the real type (double), replacing the instructions in point 3 as follows: double a = Double.parseDouble(we.readLine()); double b = Double.parseDouble(we.readLine()); 8. Run the program and check its operation 9. Inside block try... catch add further instructions to illustrate the use of built-in mathematical functions: System.out.println("square root from the number a = "+Math.sqrt(a)); System.out.println("3rd power of numbers b = "+Math.pow(b,3)); System.out.println("sinus lof number b = "+Math.sin(b)); System.out.println("Rounding of a number 3.234 = "+Math.round(3.234)); System.out.println("Rounding of a number 3.654 = "+Math.round(3.654)); 10. Then calculate and display the distance of the point with coordinates (a, b) from the point (-1, 1) by yourself. Check the operation of the program. VIII. Iterative sum calculation; entering, summing up and displaying program arguments, example of a conditional if instruction 1. Create another new project of the Java Application type, give the project a name Projekt23 and the main class - the name Sum. As a project destination, select a working folder Z:\
SSAI 2018Z: Class 1. Basics of Java programming. Page 6 of 6 2. In the content of the method main() declare the variable sum of the total type and give it its initial value 0 by means of an instruction: int sum = 0; 3. Then use the for loop to calculate the sum of the natural numbers in the range 1, 10 : for (int i = 1; i <=10; i++) { sum +=i; In the following iteration steps, the value of the variable and loop control will change from 1 (int i declaration = 1;) to 10 (condition and <= 10;) with step 1 (i++ increment operation). 4. Add an instruction displaying the calculated sum, with the comment "The sum of numbers from 1 to 10 is ". Start the program and check the displayed summation result. 5. The next task of the program will be to display the arguments of the program and calculate the sum of arguments, which are integers. Enter the program arguments by entering several integers separated by spaces in the line Arguments (command Properties Run). 6. Add an instruction displaying the number of entered program arguments in text form: "Programme has"+ args.length +" arguments" (the args.length property specifies the number of arguments) 7. Then display the values of these arguments in the for: for (int k = 0; k<args.length; k++) { System.out.println((k+1) + ": " + args[k]); 8. Correct possible errors and start the program. 9. Add another for instruction to iteratively calculate the sum of all arguments of the program that are integers: for (int i = 0; i <args.length; i++) { // i change with respect to the indexes of the array args m = Integer.parseInt(args[i]); // value of i-element assigned to a variable m sum +=m; // to add another argument to the sum Remember to clear the variable sum and declare the variable m first. Note: The args.length property specifies the length of the args array, which is the current number of arguments it contains. 10. Then add an instruction displaying the calculated sum of arguments with an appropriate comment. 11. Right-click in the code editor window and from the popup menu, select Format (or use the keyboard shortcut <Alt+Shift+F>) to align your instructions. 12. Then we will use the conditional if instruction to check if the number of arguments is even or not. int t = args.length; if( t % 2 == 0 ) System.out.println("The given number of arguments is even."); else System.out.println("The given number of arguments is odd."); 13. Correct errors and run the program.