1. 주석
System.out.print("[1,");
for (int i =2; i<n ; i++) {
if (n%i ==0){
System.out.printf("%d,",i);
}
}
System.out.println( n + "]"
int makeOne = (int)(Math.random()*10); //0~9 사이의 임의의 정수
/*
0.0<= 실수값 <10.0 을 (int)하면 정수만 반환한다.
그래서 0~9 사이의 임의의 정수를 반환한다.
*/
한 줄 주석은 //
여러 줄 주석은 /* */
2. 조건문
- if 문
if (mag >= 8.0){
}else if (mag>=7.0){
}else if (mag >= 6.0){
}else{
}
int v=100;
if (v%2==0){
System.out.println("even");
}else{
System.out.println("odd");
}
- switch case
주어진 값에 따라 분기할 때에는 switch~case를 사용한다
Public static int toNum(char c){
int tot = 0;
switch(c) {
case 'A':tot = 1; break;
case 'T':tot = 10; break;
case 'Y':tot = 15; break;
default:tot = c-'0';break;
}
return tot;
}
위의 코드는 만약 c = 'A'라면 tot에 1이 저장된다. 이 외의 문자는 숫자형 문자이므로 '0'을 빼서 나온 정수를 tot에 저장한다.
입력받은 주기에 따라 지수 종류와 바이오리듬 값을 반환할 때도 사용할 수 있다.
public static String generateTextInformation(int index, double value){
String result = "";
switch(index){
case 23:result = "신체지수 :";break;
case 28:result = "감정지수 :";break;
case 33:result = "지성지수 :";break;
}
return result + (value*100);
}
3. 반복문
- for문
for ( 초기 ; 조건 ; 스텝) {반복} 형태로 사용
i++ 을 스텝 항목에 많이 쓰는데 이는 i = i+1로 1씩 증가시킨다는 의미이다.
예제로 2345의 각 자리 숫자의 합을 구하는 코드를 구해보자
int n = 2345;
int tot = 0;
for (;n>0;){
tot = tot + n%10 ;
n = n/10 ;
}
System.out.println(tot);
위의 경우와 같이 끝나는 조건이 명확하면 초기값이나 스텝이 없을 수도 있다.
같은 예제를 while 문으로도 풀 수 있다.
- while문
조건이 명확할 땐 for 보다 while을 사용하면 좋다. 스텝이 명확하면 for, 조건이 명확하다면 while이 편하다.
위에서 푼 예제를 다시 풀어보자.
int n=2345;
int tot=0;
while(n>0){
tot = tot + n%10;
n = n/10;
}
System.out.println(tot);
4. 연산관용어구
조건문과 반복문을 함께 쓸 때 습관적으로 쓰는 코드들을 모아두었다.
- %(나머지 연산자)
나머지 연산자는 배수, 약수, 짝수, 홀수, 일의 자리를 구해야 되는 상황에서 유용하게 쓰인다.
예시)
A%3==0 : A는 3으로 나누어 떨어진다
A%2==0 짝수
A%2!=0 홀수
- /(몫 연산자)
자릿수를 줄일 때 사용한다.
123/10 = 12
3자리에서 2자리로 줄어들었다
10의 약수를 구하는 코드를 한 번 살펴보자.
Systme.out.print("[1,");
for (int i = 2; i<n ; i++) {
if (n%2 == 0){
System.out.printf("%d,",i);
}
}
System.out.println(n + "]");
5. 메소드
메소드는 선언과 호출로 나눌 수 있다.
- 선언
인자(파라미터)의 타입과 개수, 메소드 이름, 결과 반환 타입을 선언한다. 구체적인 로직이 있는 곳이다.
- 호출
인자 타입의 개수와 맞는 값을 넣고 결과를 받는 것이다.
메소드의 선언과 호출의 예시를 보자
double phyval = getBioRhythmValue(16649, 23,100);
public static double getBioRhythmValue(long days, int index, int max){
return max * Math.sin((days % index)*2*3.14/index);
}
/*
double phyval = getBioRhythmValue(16649, 23,100);
메소드 호출, 결과값 타입, 메소드 이름,메소드 인자
public static double getBioRhythmValue(long days, int index, int max){
메소드 선언
return max * Math.sin((days % index)*2*3.14/index);
}
*/
메소드는 흐름을 쉽게 만든다. 순차, 분기, 반복 흐름과 같이 사용되면서 더 많은 효과를 낼 수 있다.
- 순차 흐름과 메소드
int days = 1664:
int index = 23;
int max = 100;
double phyval = getBioRhythmValue(days, index,max);
- 조건 흐름과 메소드
if (index==23){
phyval = getBioRhythmValue(days, index, max);
} else if (index==28){
emotion = getBioRhythmValue(days,index,max);
}
- 반복 흐름과 메소드
for(int idat = days -10 ; iday<days+10 ;idays++ ){
double phybal = getBioRhythmValue(iday, index,max);
}
'프로그래밍 > Java' 카테고리의 다른 글
Java 입문 - 객체지향 프로그래밍 (0) | 2022.09.13 |
---|---|
Java 입문 - 문자열과 배열 (0) | 2022.09.13 |