본문 바로가기

콤퓨타/Programming) 왕초보 자바

14. (Loops and Conditions) Boolean + Equality

 

 

Boolean

수학자가 만들어낸 논리 추론 방법론? 이게 단순 '산수'라는 과목에서만 쓰이는게 아니라 여러 분야에서 논리성을 논할 때 쓰이는데, 프로그래밍에도 나온다. 0과 1의 분기로 갈라지고 알고리즘을 타게되는 컴퓨터의 working path style로  볼 때 boolean 을 쓰는게 맞다. 

예전 모 수업에서는  4개의 영역에서 참 거짓 참 거짓 나뉘고 어쩌고... 그랬는데.. 뭐였는지 기억이 안나지만

여튼 오늘 배운 내용에서는 내용이 단순했다. 

변수에 특정 값을 넣어두고 그 값이 참인지 거짓인지를 확인하는것. 

크다 작다에 대해서 논의했기 때문에 답을 도출해내는 것도 직관적임. 

역시 연습을 안하니까 혀가 길어지는군. 

public class App {

	public static void main(String[] args) {

		boolean condition1 = false;

		System.out.println("condition 1: " + condition1);

		// Less than
		boolean condition2 = 4 < 5;
		System.out.println("condition 2: " + condition2);

		// Greater than
		boolean condition3 = 12 < 5;
		System.out.println("condition 3: " + condition3);

	}
}

 

 

 

 

 

아래는 

챗 지피티랑 연습한 내역

public class practice_01 {

	public static void main(String[] args) {
		int myAge = 20; 
		int friendAge = 25; 
		
		boolean isOlder = myAge > friendAge; 
		System.out.println("내가 친구보다 나이가 많다:"  + isOlder);

	
		int myHeight = 180; 
		int friendHeight = 160; 
		
		boolean isTaller = myHeight > friendHeight; 
		System.out.println("내가 친구보다 키가 크다: " + isTaller);
	
		
		int myEyes = 50; 
		int friendEyes = 40; 
		boolean isBigger = myEyes > friendEyes; 
		System.out.println("나는 친구보다 눈이 크다 : " + isBigger);
		
		
		int myFingers = 11 ; 
		int friendFingers = 14;
		boolean isMore = myFingers > friendFingers; 
		System.out.println("나는 친구보다 손가락이 많다: " + isMore);
		
	}
	
	
}

 

이걸 불리안으로 돌리면 아래와 같이 나온다. 

 

명확하기 true or false 로 답이 나뉘고 있음 . 

 

 

Boolean에서 equality 를 얹은 방법

프로그래밍에서  'equal' 부호 (=) 쓸 때 주의사항
= : assign (값을 지정 )
== : equal (일반적으로 아는 '같다'의 의미) 

 

 

 

public class App {

	public static void main(String[] args) {

		int cats = 42;
		int dogs = 23;
		int weasels = 42;

		boolean moreCatsThanDogs = cats > dogs;

		System.out.println("There are more cats than dogs: " + moreCatsThanDogs);

		// Equality test operator
		System.out.printf("There are the same number of cats and weasels: %b\n ", cats == weasels);
		System.out.printf("There are the same number of cats and dogs: %b\n ", cats == dogs);

		//
		System.out.printf("Number of cats greater than number of weasels : %b\n", cats > weasels);

		// Do not use == with doubles

	}
}

 

 

 

 

여기서 중요한건 == equality 사용을 int 나 boolean에서만 쓰고

double 타입에서는 지양할 것. 

double은 소수가 나오니까 그런가?  뭔가 애매할수도 있으니 크다 작다 같다 이렇게 자연수 정수에서 명확하게 나뉠 수 있는 ? 그런걸 쓰라는 말일까 잠시 추측해보고 저는 이만... 

해피코딩....