Computers/Language java

week5. Decision

emzei 2011. 4. 10. 14:42
전용뷰어 보기

◆ Statement Types

- Simple statement

balance = balance - amount;

- Compound statement

if(condition) statement1;

- Block Statement

{

   double newBalance = balance - amount;

   balance = newBalance;

}


◆ The if/else statement

* if( condition ~ true / false) 

statement1;


◆ Comparing Values : Relational Operators

- Only for comparing NUMBER


◆ Comparing Floating-point Numbers

- To avoid roundoff errors, don't use == to compare floating-point numbers

   ( ==는 정수부만 비교하기 때문에 잘못된 결과를 만들 수 있음)

- To compare floating-point numbers test whether they are close enough : |x-y| ≤ ε

final double EPSILON = 1E-14;

if(Math.abs(x-y) <= EPSILON) //  x is approximately equal to y


 Comparing Strings

- Use equals method

if(string1.equals(string2))...

- Don't use == for strings!

      변수명(문자열 변수명)을 비교함.

== tests identity , equals tests eqaul contents

- Case insensitive test :

   if(string1.equalsIgnoreCase(string2))...



◆ Comparing Objects

- == tests for identity, equals for identical contest


 이해한다면 좋은 예제

ex.

   Rectangle box1 = new Rectangle(1,4,2,3);

   Rectangle box2 = box1;

   Rectangle box3 = new Rectangle(1,4,2,3);


box1 != box3 but box1.equals(box3)

box1 == box2


- object가 refer하는 것이 같으면 == (true), 그렇지 않으면 != (false)

- Caveat : equals must be defined for the class



 Testing for null

null reference refers to no object

use ==, not eqauls, to test for null

- null is not the same as empty string


 Multiple Alternative : Sequences of Comparisons

if(condition1)

statement1;

else if(condition2)

statement2;

...

else

statement#;


- don't omit else



◆ Using Boolean Expression 

◇ The boolean Type

- George Boole(1815-1864) : pioneer in the study of logic

- value of expression amount<1000 is true or false

boolean type : one of these 2 truth value

◇ Predicate Method

- returns a boolean value

- useful in Character class


◆ while Loop / for Loop

- Iterator를 사용한 For Loop ( Enhanced for loop )

 class EnhancedForDemo {
     public static void main(String[] args){
          int[] numbers = {1,2,3,4,5,6,7,8,9,10};
          for (int item : numbers) {
            System.out.println("Count is: " + item);
          }
     }
}

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

 

numbers이라는 array의 처음부터 끝까지 탐색함

이때의 int item은 int형 array인 numbers의 element 하나씩을 받아들여 오는 것이다.

 

 

 


 cf.

String의 length() = string의 길이 (String의 length 는 존재하지 않는다.)

Array나 Arraylist, Vector 등의 length = 칸의 길이