Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to JAVA PROGRAMMING STEPS ANALISA MASALAHNYA ANALISA MASALAHNYA INPUT-NYA APA SAJA? INPUT-NYA APA SAJA? ALGORITMA PROSESNYA BAGAIMANA? ALGORITMA.

Similar presentations


Presentation on theme: "Introduction to JAVA PROGRAMMING STEPS ANALISA MASALAHNYA ANALISA MASALAHNYA INPUT-NYA APA SAJA? INPUT-NYA APA SAJA? ALGORITMA PROSESNYA BAGAIMANA? ALGORITMA."— Presentation transcript:

1

2 Introduction to JAVA

3 PROGRAMMING STEPS ANALISA MASALAHNYA ANALISA MASALAHNYA INPUT-NYA APA SAJA? INPUT-NYA APA SAJA? ALGORITMA PROSESNYA BAGAIMANA? ALGORITMA PROSESNYA BAGAIMANA? OUTPUT-NYA APA? OUTPUT-NYA APA? KETIK SOURCE CODE-NYA KETIK SOURCE CODE-NYA HEADER FILES  import HEADER FILES  import GLOBAL SECTIONS  VARIABEL GLOBAL, FUNGSI BANTU GLOBAL SECTIONS  VARIABEL GLOBAL, FUNGSI BANTU MAIN SECTIONS  VARIABEL LOKAL, INPUT, PROSES, OUTPUT MAIN SECTIONS  VARIABEL LOKAL, INPUT, PROSES, OUTPUT COMPILE & RUN PROGRAMNYA  ADA ERROR ? COMPILE & RUN PROGRAMNYA  ADA ERROR ? TES HASILNYA  SUDAH BENAR ? TES HASILNYA  SUDAH BENAR ? BUAT ARSIP/ DOKUMENTASINYA BUAT ARSIP/ DOKUMENTASINYA

4 Computers and Programming A computer is a machine that can process data by carrying out complex calculations quickly. A computer is a machine that can process data by carrying out complex calculations quickly. A program is a set of instructions for the computer to execute. A program is a set of instructions for the computer to execute. A program can be high-level (easy for humans to understand) or low-level (easy for the computer to understand). A program can be high-level (easy for humans to understand) or low-level (easy for the computer to understand). In any case, programs have to be written following a strict language syntax. In any case, programs have to be written following a strict language syntax.

5 Running a Program Typically, a program source code has to be compiled into machine language before it can be understood by a computer. Typically, a program source code has to be compiled into machine language before it can be understood by a computer. programmer void test() { println(“Hi”); } source code (high level) compiler machine language object code (low level) writes executed by computer Hi

6 Portability Different makes of computers Different makes of computers speak different “ languages ” (machine language) speak different “ languages ” (machine language) use different compilers. use different compilers. This means that object code produced by one compiler may not work on another computer of a different make. This means that object code produced by one compiler may not work on another computer of a different make. Thus the program is not portable. Thus the program is not portable. Java is portable because it works in a different way. Java is portable because it works in a different way.

7 History of Java The Java programming language was developed at Sun Microsystems The Java programming language was developed at Sun Microsystems It is meant to be a portable language that allows the same program code to be run on different computer makes. It is meant to be a portable language that allows the same program code to be run on different computer makes. Java program code is translated into byte- code that is interpreted into machine language that the computer can understand. Java program code is translated into byte- code that is interpreted into machine language that the computer can understand.

8 Java Byte-Code Java source code is compiled by the Java compiler into byte-code. Java source code is compiled by the Java compiler into byte-code. Byte-code is the machine language for a ‘ typical ’ computer. Byte-code is the machine language for a ‘ typical ’ computer. This ‘ typical ’ computer is known as the Java Virtual Machine. This ‘ typical ’ computer is known as the Java Virtual Machine. A byte-code interpreter will translate byte-code into object code for the particular machine. A byte-code interpreter will translate byte-code into object code for the particular machine. The byte-code is thus portable because an interpreter is simpler to write than a compiler. The byte-code is thus portable because an interpreter is simpler to write than a compiler.

9 Running a Java Program programmer public void test() { System.out.println(“Hi”); } Java source code (high level) Java compiler Machine language object code (low level) writes executed by computer Hi Byte-code interpreter Java byte-code Extra step that allows for portability

10 Types of Java Programs Console Applications: Console Applications: Simple text input / output Simple text input / output This is what we will be doing for most of this course as we are learning how to program. This is what we will be doing for most of this course as we are learning how to program. public class ConsoleApp { public static void main(String[] args) { System.out.println("Hello World!"); }

11 Types of Java Programs GUI Applications: GUI Applications: Using the Java Swing library Using the Java Swing library import javax.swing.*; public class GuiApp { public static void main(String[] args) { JOptionPane.showMessageDialog(null, "Hello World!", "GUI Application", JOptionPane.INFORMATION_MESSAGE); System.exit(0); }

12 Types of Java Programs Applets Applets To be viewed using a internet browser To be viewed using a internet browser import java.applet.*; import java.awt.*; public class AppletEg extends Applet { public void paint(Graphics g) { g.drawString("Hello World!", 20, 20); } ___________________________________________________

13 Sample Java Program public class CalcCircle { public static void main(String[ ] args) public static void main(String[ ] args) { int radius;// radius - variable final double PI = 3.14159;// PI - constants radius = 10; double area = PI * radius * radius; double circumference = 2 * PI * radius; System.out.println( ” For a circle with radius ” + radius + ”, ” ); System.out.print( ” The circumference is ” + circumference); System.out.println( ” and the area is ” + area); }}

14 Elements of a Java Program A Java Program is made up of: A Java Program is made up of: Identifiers: Identifiers: variables variables constants constants Literal values Literal values Data types Data types Operators Operators Expressions Expressions

15 Identifiers The identifiers in the previous program consist of: The identifiers in the previous program consist of: public class CalcCircle { public static void main(String[] args) { int radius;// radius - variable final double PI = 3.14159;// PI - constants … } identifier indicating name of the program (class name) identifier to store the value of radius (variable) identifier to store the fixed value of PI (constant)

16 Data Types Data types indicate the type of storage required. Data types indicate the type of storage required. public class CalcCircle { public static void main(String[ ] args) { int radius;// radius - variable final double PI = 3.14159;// PI - constants … } radius is an integer (int) value PI is a floating-point (double) value

17 Literal values Literals are the actual values stored in variables or used in calculations. Literals are the actual values stored in variables or used in calculations. public class CalcCircle { public static void main(String[ ] args) { … radius = 10; … } the variable radius stores the value 10

18 Operators and Expressions Operators allow us to perform some calculations on the data by forming expressions. Operators allow us to perform some calculations on the data by forming expressions. public class CalcCircle { public static void main(String[ ] args) { … double area = PI * radius * radius; double circumference = 2 * PI * radius; … } The multiplication operator (*) is used to calculate the area An expression is formed using operators and operands

19 Java Program Structure For the next few weeks, our Java programs will have the following structure: For the next few weeks, our Java programs will have the following structure: public class CalcCircle { public static void main(String[ ] args) { // This section consists of // program code consisting of // of Java statements // } The program is a class definition – use the same name as the filename. ie. Save this file as CalcCircle.java Your program must have a main method – it will start execution from here. Curly braces indicate where sections begin and end. You should indent your code for clarity.

20 Displaying Output For console applications, we use the System.out object to display output. For console applications, we use the System.out object to display output. public class CalcCircle { public static void main(String[ ] args) { … System.out.println(”For a circle with radius ” + radius + ”,”); System.out.print(”The circumference is ” + circumference); System.out.println(” and the area is ” + area); } The text and data within the parentheses will be output to the screen.

21 Compiling and Running The preceding source code must be saved as CalcCircle.java The preceding source code must be saved as CalcCircle.java You must then use the Java Development Kit (JDK) to compile the program using the command javac CalcCircle.java You must then use the Java Development Kit (JDK) to compile the program using the command javac CalcCircle.java The byte-code file CalcCircle.class will be created by the compiler if there are no errors. The byte-code file CalcCircle.class will be created by the compiler if there are no errors. To run the program, use the command java CalcCircle To run the program, use the command java CalcCircle

22 Compiling and Runnng Buttons to compile and run the program

23 Anatomy of a Java Class A Java console application must consist of one class that has the following structure: A Java console application must consist of one class that has the following structure: /* This is a sample program only. Written by: Date: */ public class SampleProgram { public static void main(String [] args) { int num1 = 5; // num stores 5 System.out.print("num1 has value "); System.out.println(num1); } class header main method

24 Anatomy of a Java Class A Java console application must consist of one class that has the following structure: A Java console application must consist of one class that has the following structure: /* This is a sample program only. Written by: Date: */ public class SampleProgram { public static void main(String [] args) { int num1 = 5; // num stores 5 System.out.print("num1 has value "); System.out.println(num1); } multi-line comments in-line comments name of the class statements to be executed

25 What is the result of execution? public class CalcCircle { public static void main(String[ ] args) public static void main(String[ ] args) { int radius;// radius - variable final double PI = 3.14159;// PI - constants radius = 10; double area = PI * radius * radius; double circumference = 2 * PI * radius; System.out.println( ” For a circle with radius ” + radius + ”, ” ); System.out.print( ” The circumference is ” + circumference); System.out.println( ” and the area is ” + area); }}

26 Displaying output There are some predefined classes in Java that we can use for basic tasks such as: There are some predefined classes in Java that we can use for basic tasks such as: reading input reading input displaying output displaying output We use the System class to display output to the screen for console applications. We use the System class to display output to the screen for console applications. System.out is an object that provides methods for displaying strings of characters to the console screen. System.out is an object that provides methods for displaying strings of characters to the console screen. The methods we can use are print and println. The methods we can use are print and println.

27 Example Write a program that prints two lines: Write a program that prints two lines: I love Java Programming It is fun! public class PrintTwoLines { public static void main(String[] args) { System.out.println("I love Java Programming"); System.out.println("It is fun"); }

28 Print vs Println What if you use System.out.print() instead? What if you use System.out.print() instead? System.out.println() advances the cursor to the next line after displaying the required output. System.out.println() advances the cursor to the next line after displaying the required output. If you use System.out.print(), you might need to add spaces to format your output clearly. If you use System.out.print(), you might need to add spaces to format your output clearly.

29 Examples Code FragmentOutput Displayed System.out.println("First line"); System.out.println("Second line"); First line Second line System.out.print("First line"); System.out.print("Second line"); First lineSecond line

30 Exercise Write a Java program that displays your name and your studentID. Write a Java program that displays your name and your studentID. // Sandy Lim // Lecture 1 // Printing name and student ID public class Information { public static void main (String[] args) { // your code here } }

31 Exercise Write a Java program that prints out to the screen the following tree: Write a Java program that prints out to the screen the following tree: * *** *** ***** **************** // Sandy Lim // Lecture 1 // Printing a tree using * public class tree { public static void main (String[] args) { // your code here } }

32 Reminders Get your computer accounts before next week's tutorial so that you can start programming ASAP. Get your computer accounts before next week's tutorial so that you can start programming ASAP. Download JCreatorLE and J2SDK1.5.0, you can access both through the JCreator (3.50LE) website: http://www.jcreator.com/download.htm Download JCreatorLE and J2SDK1.5.0, you can access both through the JCreator (3.50LE) website: http://www.jcreator.com/download.htm http://www.jcreator.com/download.htm

33 Data Types, Variables & Operators

34 Memory and Data One of the most important components of a computer system is the memory. One of the most important components of a computer system is the memory. A computer ’ s memory holds: A computer ’ s memory holds: data that is to be processed data that is to be processed data that is the result of some processing data that is the result of some processing We can imagine that a computer ’ s memory consists of boxes to hold data. We can imagine that a computer ’ s memory consists of boxes to hold data. However, the sizes of the boxes would depend on the type of data that is held. However, the sizes of the boxes would depend on the type of data that is held.

35 Identifiers We have to give names to the boxes we are using to store data. We have to give names to the boxes we are using to store data. These names are called variable names, or identifiers. These names are called variable names, or identifiers. The actual data is the literal value of the identifier. The actual data is the literal value of the identifier. subject BIT106 value of subject identifier / variable name The box is identified as subject and it stores the value “BIT106”

36 Java Spelling Rules An identifier can consist of: An identifier can consist of: letters (A – Z, a – z) letters (A – Z, a – z) digits (0 to 9) digits (0 to 9) the characters _ and $ the characters _ and $ The first character cannot be a digit. The first character cannot be a digit.

37 Identifier Rules A single identifier must be one word only (no spaces) of any length. A single identifier must be one word only (no spaces) of any length. Java is case-sensitive. Java is case-sensitive. Reserved Words cannot be identifiers. Reserved Words cannot be identifiers. These are words which have a special meaning in Java These are words which have a special meaning in Java

38 Examples Examples of identifiers Examples of identifiers num1num2first_namelastName numberOfStudentsaccountNumber myProgramMYPROGRAM Examples of reserved words Examples of reserved words publicifintdouble see Appendix 1 in the text book for others. see Appendix 1 in the text book for others. Illegal identifiers Illegal identifiers 3rdValuemy programthis&that

39 Exercise Which of the following are valid identifier names? Which of the following are valid identifier names? my_granny ’ s_name my_granny ’ s_name joesCar joesCar integer integer 2ndNum 2ndNum Child3 Child3 double double third value third value mid2chars mid2chars PUBLIC PUBLIC

40 Types of Data What kind of data can be collected for use in a computer system? What kind of data can be collected for use in a computer system? Consider data on: Consider data on: College application form College application form Student transcript Student transcript Role Playing Game (RPG) Role Playing Game (RPG)

41 Types of Data We typically want to collect data which may be We typically want to collect data which may be numeric numeric characters characters Strings Strings choice (Y/N) choice (Y/N)

42 Java Data Types In order to determine the sizes of storage (boxes) required to hold data, we have to declare the data types of the identifiers used. In order to determine the sizes of storage (boxes) required to hold data, we have to declare the data types of the identifiers used. Integer data types are used to hold whole numbers Integer data types are used to hold whole numbers 0, -10, 99, 1001 0, -10, 99, 1001 The Character data type is used to hold any single character from the computer keyboard The Character data type is used to hold any single character from the computer keyboard '>', 'h', '8' '>', 'h', '8' Floating-point data types can hold numbers with a decimal point and a fractional part. Floating-point data types can hold numbers with a decimal point and a fractional part. -2.3, 6.99992, 5e6, 1.5f -2.3, 6.99992, 5e6, 1.5f The Boolean data type can hold the values true or false. The Boolean data type can hold the values true or false.

43 Primitive vs Reference Data Types A data type can be a: A data type can be a: Primitive type Primitive type Reference type (or Class type) Reference type (or Class type)

44 Primitive vs Reference Data Types A Primitive type is one that holds a simple, indecomposable value, such as: A Primitive type is one that holds a simple, indecomposable value, such as: a single number a single number a single character a single character A Reference type is a type for a class: A Reference type is a type for a class: it can hold objects that have data and methods it can hold objects that have data and methods

45 Java Primitive Data Types There are 8 primitive data types in Java There are 8 primitive data types in Java Type name Kind of value Memory used byteinteger 1 byte shortinteger 2 bytes intinteger 4 bytes longinteger 8 bytes float floating-point number 4 bytes double floating-point number 8 bytes char single character 2 bytes boolean true or false 1 bit

46 Declaring variables When we want to store some data in a variable, When we want to store some data in a variable, we must first declare that variable. we must first declare that variable. to prepare memory storage for that data. to prepare memory storage for that data. Syntax: Syntax: Type VariableName;

47 Declaring variables Examples: Examples: The following statements will declare The following statements will declare an integer variable called studentNumber to store a student number: an integer variable called studentNumber to store a student number: a double variable to store the score for a student a double variable to store the score for a student a character variable to store the lettergrade a character variable to store the lettergrade public static void main(String[] args) { // declaring variables int studentNumber; double score; char letterGrade;

48 Assignment Statements Once we have declared our variables, we can use the variables to hold data. Once we have declared our variables, we can use the variables to hold data. This is done by assigning literal values to the variables. This is done by assigning literal values to the variables. Syntax (for primitive types): Syntax (for primitive types): VariableName = value; This means that the value on the right hand side is evaluated and the variable on the left hand side is set to this value. This means that the value on the right hand side is evaluated and the variable on the left hand side is set to this value.

49 Assignment Statements Examples: Examples: Setting the student number, score and lettergrade for the variables declared earlier: Setting the student number, score and lettergrade for the variables declared earlier: public static void main(String[] args) { // declaring variables int studentNumber; double score; char letterGrade; // assigning values to variables studentNumber = 100; score = 50.8; letterGrade = 'D'; }

50 Initializing Variables We may also initialize variables when declaring them. We may also initialize variables when declaring them. Syntax: Syntax: Type VariableName = value; This will set the value of the variable the moment it is declared. This will set the value of the variable the moment it is declared. This is to protect against using variables whose values are undetermined. This is to protect against using variables whose values are undetermined.

51 Initializing Variables Example: the variables are initialized as they are declared: Example: the variables are initialized as they are declared: public static void main(String[] args) { // declaring variables int studentNumber = 100; double score = 50.8; char letterGrade = 'D'; }

52 Arithmetic Operators We can use arithmetic operators in our assignment statements. We can use arithmetic operators in our assignment statements. The Java arithmetic operators are: The Java arithmetic operators are: addition, +(integer and floating-point) addition, +(integer and floating-point) subtraction, -(integer and floating-point) subtraction, -(integer and floating-point) multiplication, * (integer and floating-point) multiplication, * (integer and floating-point) division, / (integer and floating-point) division, / (integer and floating-point) modulus, %(integer division to find remainder) modulus, %(integer division to find remainder)

53 Arithmetic Operators Example: using the + operator Example: using the + operator public static void main(String[] args) { // declaring two integer variables int num1 = 5, num2 = 8; // declaring a variable to store the total int total; // performing addition: total = num1 + num2; // display result System.out.println(“total = “ + total); }

54 Arithmetic Expressions More examples of expressions: More examples of expressions: public static void main(String[] args) { // declaring variables int num1 = 5, num2 = 8; int quotient, remainder; double total, average; // performing arithmetic: total = num1 + num2; average = total / 2;// floating-point division quotient = num1 / num2;//integer division remainder = num1 % num2; // how to display the results? }

55 Operator Precedence Operators follow precedence rules: Operators follow precedence rules: Thus you should use parentheses ( ) where necessary. Thus you should use parentheses ( ) where necessary. Generally according to algebraic rules: Generally according to algebraic rules: ( ), *, /, %, +, - ( ), *, /, %, +, -

56 Operator Precedence Example: Example: The expressions The expressions 3 + 5 * 5 will evaluate to 28 3 + 5 * 5 will evaluate to 28 (3 + 5) * 5 will evaluate to 40 (3 + 5) * 5 will evaluate to 40

57 Assignment Compatibilities In an assignment statement, you can assign a value of one type into another type: In an assignment statement, you can assign a value of one type into another type: int iVariable = 6; double dblVariable; dblVariable = iVariable; // assigning int to double

58 Assignment Compatibilities However, you can not directly assign a double into an int However, you can not directly assign a double into an int double dblVariable = 6.75; int iVariable; iVariable = dblVariable; // assigning double to int Compiler error! Possible loss of precision

59 Type Casting Generally, you can only assign a type to the type appearing further down the list: byte > short > int > long > float > double Generally, you can only assign a type to the type appearing further down the list: byte > short > int > long > float > double However, if you wish to change a double type to an int, you must use type casting However, if you wish to change a double type to an int, you must use type casting

60 Type Casting: Example The value of iVariable is now 6 The value of iVariable is now 6 The value of dblVariable is truncated and assigned to iVariable. The value of dblVariable is truncated and assigned to iVariable. The value of dblVariable remains 6.75 The value of dblVariable remains 6.75 double dblVariable = 6.75; int iVariable; iVariable = (int) dblVariable; // assigning double to int by typecasting

61 Sample Program Let's have a look at the following program. What does it do? Let's have a look at the following program. What does it do? public class SimpleMaths { public static void main (String[] args) { int num1 = 5, num2 = 6; int sum, diff, product, quotient, remainder; sum = num1 + num2; diff = num1 - num2; product = num1 * num2; quotient = num1 / num2; remainder = num1 % num2; }

62 Displaying output We must use display the results obtained We must use display the results obtained public class SimpleMaths { public static void main (String[] args) { int num1 = 5, num2 = 6; int sum, diff, product, quotient, remainder; sum = num1 + num2; diff = num1 - num2; … System.out.println(sum); System.out.println(diff); // etc } displays the value stored in the variable sum

63 Displaying output However, we should always make our output meaningful and clear. However, we should always make our output meaningful and clear. public class SimpleMaths { public static void main (String[] args) { int num1 = 5, num2 = 6; int sum, diff, product, quotient, remainder; sum = num1 + num2; … System.out.println("The sum is"); System.out.println(sum); // etc }

64 Displaying output We can use the System.out.print() method: We can use the System.out.print() method: public class SimpleMaths { public static void main (String [] args) { int num1 = 5, num2 = 6; int sum, diff, product, quotient, remainder; sum = num1 + num2; … System.out.print("The sum is "); System.out.println(sum); // etc }

65 Displaying output We can combine Strings and data using the concatenation operator + We can combine Strings and data using the concatenation operator + public class SimpleMaths { public static void main (String [] args) { int num1 = 5, num2 = 6; int sum, diff, product, quotient, remainder; sum = num1 + num2; … System.out.print("The sum is " + sum); // etc }

66 Concatenation + The symbol '+' has two meanings in Java The symbol '+' has two meanings in Java Addition plus, which adds two numbers Addition plus, which adds two numbers Concatenation plus, which joins Strings or text together. Concatenation plus, which joins Strings or text together.

67 Concatenation + '+' will be used for addition if: '+' will be used for addition if: both operands are numeric both operands are numeric System.out.println(8 + 6); System.out.println(17.5 + 4); System.out.println("8" + 6); System.out.println(8 + "6”) System.out.println("8" + "6”) System.out.println("The answer is " + 14); System.out.println("The answer is " + 8 + 6); '+' will be used to concatenate if: '+' will be used to concatenate if: if either operand is a String or text if either operand is a String or text

68 Exercise Write a Java program that sets the values of three integer-valued assignment scores and then calculates and displays: Write a Java program that sets the values of three integer-valued assignment scores and then calculates and displays: the total of the three scores the total of the three scores the average of the three scores the average of the three scores

69 Exercise What is wrong with the following program? What is wrong with the following program? public class countAvg { public static void main (String[] args) { int score1, score2; double average = 0.0; score1 = 56; score2 = 73; average = score1 + score2 / 2 System.out.print("The average of "); System.out.print(score1); System.out.print("and"); System.out.println(score2); System.out.println("is " + average); }

70 The Char data type Another primitive data type is char Another primitive data type is char The char data type can hold values of the following character literals: The char data type can hold values of the following character literals: the letters of the alphabet, eg.: 'A', 'b' the letters of the alphabet, eg.: 'A', 'b' the digits, eg. : '0', '3' the digits, eg. : '0', '3' other special symbols, eg.: '(', '&', '+' other special symbols, eg.: '(', '&', '+' the null (empty) character: '' the null (empty) character: ''

71 The Char data type Invalid character literals: Invalid character literals: "a" – this is a string "a" – this is a string 'aB' – these are two characters 'aB' – these are two characters ''' – three consecutive single quotes: ''' – three consecutive single quotes: what does it mean? what does it mean?

72 Escape Sequence Sometimes it is necessary to represent symbols: Sometimes it is necessary to represent symbols: which already have special meanings in the Java language, such as ' or " which already have special meanings in the Java language, such as ' or " other characters such as a tab or return. other characters such as a tab or return.

73 Escape Sequence The escape sequence character \ is used in this case. The escape sequence character \ is used in this case. '\'' to represent the single quote character '\'' to represent the single quote character '\"' to represent the double quote character '\"' to represent the double quote character '\\' to represent a backslash character. '\\' to represent a backslash character. '\t' to represent a tab '\t' to represent a tab '\n' to create a new line '\n' to create a new line

74 Exercise Write a program that will display the following: Write a program that will display the following: She said "Hello!" to me! She said "Hello!" to me!

75 The String Data Type A String type is an example of a reference data type. A String type is an example of a reference data type. A string is defined as a sequence of characters. A string is defined as a sequence of characters.

76 The String Data Type Examples of String literals: Examples of String literals: " " (space, not the character ' ') " " (space, not the character ' ') "" (empty String) "" (empty String) "a" "a" "HELLO" "HELLO" "This is a String" "This is a String" "\tThis is also a String\n" "\tThis is also a String\n"

77 Declaring a String Strings can be used to store names, titles, etc. Strings can be used to store names, titles, etc. We can declare a String data type by giving it a variable name: String name; We can declare a String data type by giving it a variable name: String name; We can also initialize the variable upon declaration: String subjectCode = “BIT106”; We can also initialize the variable upon declaration: String subjectCode = “BIT106”;

78 Exercise Write a program to print out the following, using String variables: Subject code: BIT106 Subject name: Java Programming Student name: Lee Ah Yew Assignment 1 Score (out of 25): 24.0 Assignment 2 Score (out of 25): 23.5 Exam Raw Score (out of 50) : 48.90 Write a program to print out the following, using String variables: Subject code: BIT106 Subject name: Java Programming Student name: Lee Ah Yew Assignment 1 Score (out of 25): 24.0 Assignment 2 Score (out of 25): 23.5 Exam Raw Score (out of 50) : 48.90 Lee Ah Yew's Total Score for BIT106 (Java Programming): 96.40

79 Keyboard Input Java 5.0 has reasonable facilities for handling keyboard input. Java 5.0 has reasonable facilities for handling keyboard input. These facilities are provided by the Scanner class in the java.util package. These facilities are provided by the Scanner class in the java.util package. A package is a library of classes. A package is a library of classes.

80 Using the Scanner Class Near the beginning of your program, insert Near the beginning of your program, insert import java.util.* Create an object of the Scanner class Create an object of the Scanner class Scanner sc = new Scanner (System.in) Read data (an int or a double, for example) Read data (an int or a double, for example) int n1 = sc.nextInt(); double d1 = sc.nextDouble();

81 Keyboard Input Demonstration class ScannerDemo class ScannerDemo

82 Some Scanner Class Methods syntax syntax Int_Variable = Object_Name.nextInt(); Double_Variable = Object_Name.nextDouble(); String_Variable = Object_Name.next(); String_Variable = Object_Name.nextLine(); Remember to prompt the user for input, e.g. Remember to prompt the user for input, e.g. System.out.print(“Enter an integer: “);

83 Interactive Input You should always prompt the user when obtaining data: You should always prompt the user when obtaining data: Please enter your name: Sandy Lim Please enter your age: 25 Please enter your score: 87.9 Please enter your grade: A

84 Exercise Write a program that asks the user to enter the name of an item, the price and the quantity purchased. The program must calculate the total price and display the following: Write a program that asks the user to enter the name of an item, the price and the quantity purchased. The program must calculate the total price and display the following: ItemUnitQty Total widget RM5.3010 RM53.00

85 Pseudocode When we want to write a computer program, we should always: When we want to write a computer program, we should always: Think Think Plan Plan Code Code We can write out our planning using pseudocode – writing out the steps in simple English and not strict programming language syntax. We can write out our planning using pseudocode – writing out the steps in simple English and not strict programming language syntax.

86 Documentation A computer programmer generally spends more time reading and modifying programs than writing new ones. A computer programmer generally spends more time reading and modifying programs than writing new ones. It is therefore important that your programs are documented: It is therefore important that your programs are documented: clearly clearly neatly neatly meaningfully meaningfully

87 Documentation You should always precede your program with: You should always precede your program with: Your name Your name The date The date The purpose of the program The purpose of the program

88 Comments Comments are used to: Comments are used to: Insert documentation Insert documentation Clarify parts of code which may be complex. Clarify parts of code which may be complex. Comments are ignored by the compiler but are useful to humans. Comments are ignored by the compiler but are useful to humans.

89 Comments The symbols // are used to indicate that the rest of a line are comments. The symbols // are used to indicate that the rest of a line are comments. If comments span more than one line, the symbols /* and */ can be used, eg.: /* this is the beginning of the documented comments and it only ends here */ If comments span more than one line, the symbols /* and */ can be used, eg.: /* this is the beginning of the documented comments and it only ends here */

90 Variable names Variable names shoud: Variable names shoud: follow the Java rules follow the Java rules be meaningful be meaningful For example, name, score, totalBeforeTaxes For example, name, score, totalBeforeTaxes You should almost never use names like a, b, c You should almost never use names like a, b, c

91 Variable names By convention: By convention: variable names start with a lowercase letter variable names start with a lowercase letter class names start with an uppercase letter, eg. String, Scanner class names start with an uppercase letter, eg. String, Scanner

92 Indentation Programs are also indented for clarity Programs are also indented for clarity Indentation shows the levels of nesting for the program. Indentation shows the levels of nesting for the program. public class CalcCircle { public static void main(String[] args) { int radius;// radius - variable final double PI = 3.14159;// PI - constants radius = 10; double area = PI * radius * radius; double circumference = 2 * PI * radius; } }

93 Exercise Write a program that asks the user for their name and the year they were born. Then display their age this year. Write a program that asks the user for their name and the year they were born. Then display their age this year. What is your name? Kelly What is your year of birth? 1982 Wow, Kelly, this year you will be 21 years old!

94 Exercise Write a program that asks the user to enter the length and width of a rectangle and then display: Write a program that asks the user to enter the length and width of a rectangle and then display: the area of the rectangle the area of the rectangle the perimeter of the rectangle the perimeter of the rectangle

95 The Math class: We can use pre-defined methods from the Math class to perform calculations.

96 Exercise Write a Java program that asks the user to enter two numbers, then: Write a Java program that asks the user to enter two numbers, then: find the absolute value of each of the numbers; find the absolute value of each of the numbers; determine which absolute value is larger determine which absolute value is larger find the square root of the larger of the two absolute values find the square root of the larger of the two absolute values Sample run: Enter first number: -36 Enter second number: 5 The absolute values of the two numbers are 36 and 5 The larger absolute value is 36 The square root of 36 is 6.0

97 Catch-up Exercise Write a Java program that asks the user to enter a double number. Then display: Write a Java program that asks the user to enter a double number. Then display: the square root of the number. the square root of the number. Now test the program with the values: Now test the program with the values: 39.4 39.4 -30 -30 We want to be able to make sure that the user cannot enter negative values! We want to be able to make sure that the user cannot enter negative values!


Download ppt "Introduction to JAVA PROGRAMMING STEPS ANALISA MASALAHNYA ANALISA MASALAHNYA INPUT-NYA APA SAJA? INPUT-NYA APA SAJA? ALGORITMA PROSESNYA BAGAIMANA? ALGORITMA."

Similar presentations


Ads by Google