1. Trang chủ
  2. » Công Nghệ Thông Tin

Java C2. Programming Basics docx

61 393 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Programming Basics
Tác giả Cao Tuan-Dung, Samuel A. Rebelsky, Florence Balagtas
Trường học Hanoi University of Technology
Chuyên ngành ITSS Java Programming
Thể loại Bài tập lớn
Thành phố Hanoi
Định dạng
Số trang 61
Dung lượng 412 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

 Tool that pulls out the class and the method etc., defined in the source file, and creates the reference manual of the program  Main tag of ‘javadoc’  @see Reference destination nam

Trang 1

Chapter 2 Programming

Basics

ITSS Java Programming

CAO Tuan-Dung, HUT

Trang 2

 Explanation to improve readability of program

 // comments one line

 int nquest; // number of questions

 /* */ comments multiple lines

 javadoc comments

program to produce HTML documentation for the program

Trang 3

 Tool that pulls out the class and the method etc.,

defined in the source file, and creates the reference manual of the program

 Main tag of ‘javadoc’

 @see Reference destination name : Make the reference link of other classes and related packages from the class

of the object

 @exception Explanation of exception class name:

Describe the explanation of the exception that the

method of object has possibility to throw

 @param Explanation of argument name

 @return The explanation of the return value of the

method of the object is described

Trang 4

Hand on Lab: Javadoc

java program named: Circle.java

slides

 javadoc –private Circle.java

 javadoc -author -version Circle.java

Trang 5

public class Circle {

/** The current color of the circle */

protected Color color;

/** The current diameter of the circle */

protected int diameter;

Trang 6

x-this.diameter/2, // Left margin

y-this.diameter/2, // Top margin

Trang 7

Result

Trang 8

methods, classes

 This means that the identifier Hello is not the same as hello.

underscore “_”, or a dollar sign “$” Letters may be lower or upper case Subsequent

characters may use numbers 0 to 9

Trang 9

class, public, void, etc.

Trang 10

Coding guidelines – Naming Rule

 For names of classes, capitalize the first letter of

the class name For example,

 For names of methods and variables, the first letter

of the word should start with a small letter For

example,

 The basic data type constant is all capital letters

and the object constant is all small letters,

 MAX_LENGTH, TAX_VALUE, Color.red, System.out

Trang 11

Java keywords

by Java for a specific purpose You cannot

use keywords as names for your variables, classes, methods etc

Trang 12

Java keywords

abstract assert boolean break byte case catch char class const continue default do

double

else enum extends false final finally float for goto if implements import

instanceof int

interface long

native new null package private protected public return short static strictfp super

switch synchronized this

throw throws transient true

try void volatile while

Trang 13

Primitive Data

 There are eight primitive data types in Java

 Four of them represent integers:

 Two of them represent floating point numbers:

Trang 14

Numeric Primitive Data

primitive types is their size, and therefore the values they can store:

> 9 x 10 18

Trang 15

to a lot of natural languages.

Trang 16

 A variable is a name for a location in memory

variable's name and the type of information that it will hold

int total;

int count, temp, result;

Multiple variables can be created in one declaration

Trang 17

Character Strings

 A string of characters can be represented as a string literal

by putting double quotes around the text:

 Examples:

"This is a string literal."

 Every character string is an object in Java, defined by the String class Every string literal represents a String

Trang 19

Basic data type and reference type

Java:

 Primitive Variables

 Reference Variables

 Variables with primitive data

types such as int or long

 Stores data in the actual

memory location of where the

Trang 20

Basic data type and reference type

 variables that stores the address in the

memory location

 points to another memory location where

the actual data is

class, you are actually declaring a

reference variable to the object with that certain class

Trang 21

Reference type

 int num = 10; // primitive type

 String name = "Hello"; // reference type

Trang 23

 Decimal Expression: 0.23445 or 0.23445F (float type)

 Exponent (Scientific) Expression: 6.02E13

Trang 24

Java Literal

 Boolean literals have only two values, true or false

 Character literals: ‘a’, ‘\t’, ‘\u3042’

 String literal: “Go ahead!”

 Null literal (reference type)

Trang 27

Increment and Decrement

 The increment and decrement operators use only one operand

 The increment operator (++) adds one to its operand

 The decrement operator ( ) subtracts one from its operand

 The statement

count++;

is functionally equivalent to

count = count + 1;

Trang 28

Relational & Logic Operators

 Relational operators: judges the equivalence or bigness and smallness of two expression and variables

 == (equal) , <= (less than) , >= (more than) , != (not equal), >

(bigger), < (smaller)

 Logic operators

 && (logical AND)

 & (boolean logical AND)

 || (logical OR)

 | (boolean logical inclusive OR)

 ^ (boolean logical exclusive OR)

 ! (logical NOT)

Trang 29

Hand on

public class TestAND { public static void main( String[] args ) {

Compile and Run

Trang 30

Logical Operators: &&(logical) and &(boolean logical) AND

 The basic difference between && and & operators :

&& supports short-circuit evaluations (or partial

evaluations), while & doesn't

 Given an expression:

exp1 && exp2

 && will evaluate the expression exp1, and immediately return a false value is exp1 is false

 If exp1 is false, the operator never evaluates exp2

because the result of the operator will be false regardless

of the value of exp2

 In contrast, the & operator always evaluates both exp1 and exp2 before returning an answer.

Trang 31

Ternary – instanceof operator

 Ternary operator: returns a value that is different according

to the truth of conditional expression

Format: Conditional expression ? value A:value B

 instanceof operator: The ‘instanceof’ operator is an operator that judges if an object is a product generated from a class

Format: object instanceof class

Trang 33

Type casting

 Implicit type casting: When operating on values of different data types, the lower one is promoted to the type of the higher one

int intVal = 123;

long longVal = 213000L;

longVal = intVal;

 Explicit type casting: the type is put in parentheses in front

of the value being converted

point result when dividing them, we can cast total:

result = (float) total / count;

Trang 34

Each value has a numeric index

This array holds 10 values that are indexed from 0 to 9

Trang 37

Operation of array

 In order to get the number of

elements in an array, you can use the

length field of an array

arrayName.length

 Copy of array:

 System.arraycopy(Object

org, int org_index, Object

dest, int dest_index, int

Trang 38

Array of reference type

is "array of the variable that refers to the

object", and that it is not "array of the

object".

 String array[] = new String[5];

 array[0] = “Chao”;

Trang 39

Multidimensional Array

 Multidimensional arrays are implemented as arrays of arrays

 Example

// integer array 512 x 128 elements

int[][] twoD = new int[512][128];

// character array 8 x 16 x 24

char[][][] threeD = new char[8][16][24];

// String array 4 rows x 2 columns

String[][] dogs = {{ "terry", "brown" },

{ "Kristin", "white" }

{ "toby", "gray"},

{ "fido", "black"}

Trang 40

Caution with System.copyarray

int array1[][] = new int[3][5];

int array1[][] = new int[3][5];

int array2[][] = new int[3][5];

// Copy all elements of ‘array1’ onto ‘array2’

Trang 41

Command line arguments

application‘s starting

 public static void main(String args[]){…}

 Use: java classname args[0] args[1] args[2]

 prompt>java Introduce HuuBinh 21;

public static void main(String args[]){

if (args.length ==2){

System.out.println(“My name: “ + args[0]);

System.out.println(“I am “ + args[1] + “years old.”);

Trang 42

The if-else Statement

 An else clause can be added to an if statement to make an if-else statement

if ( condition ) statement1; else

statement1

true false

statement2

Trang 43

Example: Calculate wages

import java.text.NumberFormat;

import java.util.Scanner;

public class Wages{

public static void main (String[] args) {

final double RATE = 8.25; // regular pay rate

final int STANDARD = 40; // standard hours in a work week

Scanner scan = new Scanner (System.in);

double pay = 0.0;

System.out.print ("Enter the number of hours worked: ");

int hours = scan.nextInt();

Trang 44

The switch Statement

is: switch ( expression )

{ case value1 : statement-list1

case value2 : statement-list2

words

If expression matches value2,

control jumps

to here

Trang 45

The switch Statement

 Often a break statement is used as the last statement in each case's statement list

 A break statement causes control to transfer to the end of the switch statement

 If a break statement is not used, the flow of control will continue into the next case

 Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

Trang 46

Question: What is the result of this code?

}

Trang 47

The for Statement

 A for statement has the following syntax:

for ( initialization ; condition ; increment ) statement;

The initialization

is executed once before the loop begins

The statement is

executed until the

condition becomes false

The increment portion is executed

at the end of each iteration

for (int count=1; count <= 5; count++)

Trang 48

For each statement

for (variable : arr) {

Trang 49

Hand on Lab

and the mean value (float) when an int type 1-dimension array is given

Trang 50

int sum = 0; // Total value

for(int i=0; i<data.length; i++){

// Calculation of total

sum += data[i];

}

/* Use extension loop ‘for’

for(int num : data){

sum += data;

}*/

float ave = sum/10.0f;

// (Another solution) float ave = (float)sum/10;

System.out.println(“Sum :” + sum);System.out.println("Ave :" + ave);}

}

Trang 51

Hand on Lab

program display the Min, Max value of the array

Trang 52

while and do while statement

The while Loop

true

condition evaluated statement

false The do Loop

Trang 53

break and continue

 break: exit from the iteration

 continue: Returns to the head of repetition

 question: What is the output of the following code?

public class BreakContinue{

public static void main(String argv[])

Trang 54

Enumerated type

 Type to define related two or

more strings collectively

 Definition

 [Modifier] enum Enumeration

type-identifier { Element1, Element2,

Element 3,… Element n}

 Use

 [Modifier] enum Enumeration

type-identifier Variable name;

 Variable name = Enumeration

os = OperatingSystems.windows;

switch(os) { case windows:

System.out.println("You chose Windows!");

Trang 55

Reading Simple Input

 For simple testing, use standard input

 Note that you need import statement See next slide!

Scanner inputScanner = new Scanner(System.in); int i = inputScanner.nextInt();

double d = inputScanner.nextDouble();

 Convert explicitly (Integer.parseInt, Double.parseDouble)

String seven = "7";

int i = Integer.parseInt(seven);

 In real applications, use a GUI

 Collect input with textfields, sliders, combo boxes, etc.

 Convert to numeric types with Integer.parseInt, Double.parseDouble, etc.

Trang 56

import java.util.*;

public class RandomNums {

public static void main(String[] args) {

System.out.print("How many random nums? ");

Scanner inputScanner = new Scanner(System.in); int n = inputScanner.nextInt();

for(int i=0; i<n; i++) {

System.out.println("Random num " + i +

" is " + Math.random());

} }

}

Trang 57

Hands on Lab

program that calculates ‘b’ multiplication of ‘a’ However, assume that ‘a’

is a discretionary integer and ‘b’ is an integers of 0 or more If the

number of parameters from the command line is insufficient or too

much, or if a negative value is input to ‘b’, output the error message to terminate the program.

Trang 59

class Power {

public static void main(String args[]) {

// Check on parameter number

// Making of parameter integer

int a = Integer.parseInt( args[0] );

System.exit(-1);

} long res = 1; // Result of calculation long // Calculation of power

for(int i=0; i<b; i++) {

res *= a;

} // Display of result System.out.println(args[1] + “power of” + args[0] + ”is” + res + “.”);

} }

Trang 60

Hand on Lab

three times in a certain company Examinees were five people (Okada, Tamura, Matsuda, Asai,and Natsuki), and the score was Okada {79, 65, 78} , Tamura {21, 93, 45}, Matsuda {31, 55, 22}, Asai {81, 66, 81},

and Natsuki {76, 90, 86} The test results and the examinees' names

are stored in the array as follows.

String name[] = {"Okada", "Tamura", "Matsuda", "Asai",

"Natsuki"};

int data[][] = {{79, 65, 78}, {21, 93, 45}, {31, 55, 22}, {81,

66, 81}, {76, 90, 86}};

a bar chart that shows the degrees of their achievement The bar chart shows the degree of chievement by the number of '*', and records one '*' for 10 points of the average score

Trang 61

// Array that stores total points

int sum[] = new int[5];

// Calculation of total

for(int i=0;i<5;i++) {

for(int j=0;j<3;j++) { sum[i] += data[i][j];

} }

for(int i=0;i<5;i++) { // '*'Calculation of number int stars = ( sum[i] / 3 ) / 10;

// Display of names System.out.print("Name:" + name[i] + " "); // Display of average score

System.out.print("Ave :" + sum[i]/3.0f + " "); // Display of achievement degree

for(int j=0;j<stars;j++){ { System.out.print('*');

} System.out.println();

} }

Ngày đăng: 28/06/2014, 03:20