[JAVA]/생활코딩

[생활코딩] 숫자와 연산, 문자열, 변수, casting

hatch 2021. 7. 7. 19:26
728x90
반응형

#210707#숫자와연산#문자열#변수#casting

1. 숫자와 연산

1) 오늘 배운 내용

public class Number {

	public static void main(String[] args) {
		//Operator = 연산자
		System.out.println(6+2); //8
		System.out.println(6-2); //4
		System.out.println(6*2); //12
		System.out.println(6/2); //3
		
		System.out.println(Math.PI); //3.141592653589793
		System.out.println(Math.floor(Math.PI)); //floor = 정수로 반내림, 3.0
		System.out.println(Math.ceil(Math.PI)); //ceil = 정수로 반올림, 4.0
	}

}

- 프로젝트 형성(: 우클릭 > new > java project), 클래스 형성(: 해당 프로젝트에서 우클릭 > new > class)

- 연산자경험, 사칙연산 수행함.

- 좀 더 쉽게 연산할 수 있는 함수, Math.~

  Math.PI = 파이 값 나옴. / floor 혹은 ceil을 통해 정수값으로 반내림, 반올림 가능.

 >> c언어

   a. 동일한 함수 사용

   (외부 라이브러리 선언(#include <math.h>) 후 ceil(); / floor();)

   b. round 사용

   c. 직접 반올림/반내림 함수 제작(변수 입력 받아 +0.5..)

 

2. 문자열

1) 내용 요약

public class StringApp {

	public static void main(String[] args) {
		System.out.println("Hello world"); //String, 문자열
		System.out.println('H'); //Character = '', 한 글자만 사용할 때.

		System.out.println("Hello "
				+ "world");
		// new line
		System.out.println("Hello \nworld");
		
		//escape
		System.out.println("Hello \"world\"");
	}

}
public class StringOperation {

	public static void main(String[] args) {
		System.out.println("Hello world".length()); //1억 글자라고 생각, 해당 문자 길이 알 수 있음.
		System.out.println("Hello, [[[name]]]... bye.".replace("[[[name]]]", "egoing"));
	}

}

- string 과 character 차이: ("문자열") / ('한') 글자

- 특이하게 "Hello + world" 가능, 물론 줄바꿈이 되지는 않는다.

- 줄바꿈: \n (c언어와 동일)

- "" 문자를 그대로 쓰고 싶다면? \(역 슬래시 붙이기, c언어와 동일)

- 문자열 길이 세는 함수(?) .length();

- 특정 문자열 치환할 수 있는 .replace();

  >> c언어

   a. string.h에 replace(); 없음.

   (나) 문자열 변수 설정, 치환하는 방식..?

 

3. 변수

1) 오늘 배운 내용

//변수와 데이터 타입 일치시키기
public class Variable {

	public static void main(String[] args) {
		int a = 1; //Number -> integer(int): 정수.
		System.out.println(a);
		
		double b = 1.1; //real number -> double : 실수형.
		System.out.println(b);
		
		String c = "Hello world";
		System.out.println(c);
	}
}
// 문자열 변수
public class Letter {

	public static void main(String[] args) {
		String name = "egoing"; //문자열 변수 설정. 어떤 취지로 썼는지도 파악 가능.
		System.out.println("Hello, "+name+"... egoing ... bye.");

		System.out.println(10); //다른 사람은 코드 의미 모름.
		
		double VAT = 10.0; //부가 가치세 세율이구나!
		System.out.println(VAT);
	}
}

- 변수

  a. 목적: 모두가 알아볼 수 있는 이름 부여해서 코드 의미 파악할 수 있게 하기 위함.

  >> 나만 알아볼 수 있는 변수? 좋지 않다.

 

  b. 변수, 데이터 타입 일치시키는 이유

  : 변수에 따라 데이터 타입 약속하면 어떤 데이터를 담고 있고 어디에서 쓰이는지 바로 볼 수 있음.

 

- 실수를 표현하기 위한 자료형: double / float

  >> float와 double의 차이(java)

(출처: https://imasoftwareengineer.tistory.com/50 [삐멜 소프트웨어 엔지니어])

  float, 32비트를 가지고 실수를 표현. 소수점뒤에 f를 붙여서 사용(ex. 0.0001f ).

 double, 64비트를 가지고 실수를 표현. f를 붙여주지 않아도 소수점을 표현 할 수 있다.  

 

cf. 부동소수점 표현방식: 어떤 수를 과학에서 유효숫자를 표현하듯 (예를들어 130 = 1.3 * 10^2) 이진수 또한

사용 가능한 비트를 지수부와 가수부로 나누어 지수부에서는 지수(2^n)를 표현하고 가수부는 말 그대로 x.xxxx부분을 표현하는 것.

float / double 모두 부동 소수점의 정확성(Precision)문제가 나타남. (나) 계산 오류

 

4. Casting(데이터 타입 변환)

1) 오늘 배운 내용

public class Casting {

	public static void main(String[] args) {
		double a = 1.1;
		double b = 1;
		//명시적으로 한다면
		double b2 = (double) 1;
		System.out.println(b); //1.0으로 자동변환됨. 손실 없어서 가능.
		
		//int c = 1.1; > data손실 때문에 오류.
		double d = 1.1;
		int e = (int) 1.1; //강제로 int처리.
		System.out.println(e);
		
		// 1 to String (검색해보자)
		String f = Integer.toString(1); //int > string
		System.out.println(f);
	}
}

- 손실이 없다면 자동 변환, 손실 생기면 오류.

- 오류 처리 방법

  a. (원하는 데이터 타입) 값;

       값 앞에 강제로 괄호를 씌운 데이터 타입을 둔다.

  b. 순응하고 맞는 데이터 타입으로 바꾼다. (ex. int d = 1.1 > double d = 1.1)

 

  >> 그 외 데이터 변환을 하고 싶을때?

  검색 > 적용 > 익숙해지기

  cf. System.out.println(f.getClass());  / .getClass(); 제대로 형변환 되었는지 확인할 수 있음.

 

2) '명시적인' 프로그래밍?

 a. 개발자가 이런 환경에서는 이렇게 반응하고, 저런 환경에서는 저렇게 반응하도록 만드는 것.

 (출처: https://forensics.tistory.com/4)

 b. rule based programming. C++, 알고리즘과 같이 어떠한 조건에 따라 수행되는 프로그램

 (출처: https://ppomelo.tistory.com/74 [ppomelo 🍐])