- 배열 변수를 배열 변수에 대입하기

		int intArr[] = new int[5];
		int mArr[] = intArr;
		
		for(int i = 0 ; i < 5 ; i++) {
			intArr[i] = i;
		}
		
		for(int j = 0 ; j < 5 ; j++) {
			System.out.println(intArr[j]);
		}
		System.out.println("------------");		
		for(int k = 0 ; k < 5 ; k++) {
			System.out.println(mArr[k]);
		}
		System.out.println("------------");
		mArr[2] = 100;
		for(int j = 0 ; j < 5; j++) {
			System.out.println(intArr[j]);

mArr[2]에 100을 대입했기 때문에 inArr[2]에도 100이 대입된다.

같은 공간을 공유하기 때문이다.

 

- 배열의 최대값, 최소값 비교

		System.out.println("숫자 5개를 입력하세요.");
		
		
		int numArr[] = new int[5];
		
		//5개 숫자 입력 처리
		for(int i = 0 ; i < 5 ; i++) {
			numArr[i] = scan.nextInt();
		}
		
		
		//최대값/최소값 찾기
		int max = 0, min = 9999;
								
		
		for(int j = 0; j < 5; j++) {
			//최대값 비교
			if(max < numArr[j]) {
				max = numArr[j];
			}
			
			
			//최소값 비교
			if(min > numArr[j]) {
				min = numArr[j];
			}
		}
		
		System.out.println("가장 큰 값은 : " + max);
		System.out.println("가장 작은 값은 : " + min);

최대값, 최소값 변수에 값을 지정해줄 때는 최소값에는 가장 큰 값을 대입해놓고, 최대값에는 가장 작은 값을 넣어준다.

이유는 수치 두개를 만들어놓고, 첫번째 값과 비교하면 무조건 첫번째 값이 최대값이나 최소값에 대입되기 때문이다.

다른 방법으로는 아예 배열의 첫번째 값을 대입해주는 방법도 있다.

 

- 버블 정렬

import java.util.*;

public class BubbleSort {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		
		int numArr[] = { 8, 23, 100, 26, 1 };
		
		System.out.print("정렬 전 : ");
		for(int n : numArr) {
			System.out.print(n + " ");
		}
		System.out.println();//단순 줄 바꿈 처리
		
		//버블 정렬
		int temp = 0;
		//배열의 크기를 구하는 키워드
		//배열이름.length
		
		System.out.println("배열의 크기 : " + numArr.length);
		
		for(int i = 0; i < numArr.length; i++) {//라운드횟수(0~5까지)
			for(int j = 0; j < numArr.length-i-1; j++) {//(0~4까지)
				if(numArr[j] > numArr[j + 1]) { 
					temp = numArr[j];			
					numArr[j] = numArr[j+1];	
					numArr[j+1] = temp;			
				}
			}	
		}
		System.out.print("버블 정렬 후 : ");
		for(int n : numArr) {
			System.out.print(n + " ");
		}
	}
}

옆 배열과의 숫자를 비교해서 좌우교환 후 순서대로 정렬하는 방법

8 23 100 26 1

                           

1 8 23 26 100

 

- 선택 정렬

public class SelectionSort {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int numArr[] = { 8, 23, 100, 26, 1 };
		int min; //최소값을 가진 데이터의 인덱스 저장 변수
        int temp;
        
        System.out.print("정렬 전 : ");
		for(int n : numArr) {
			System.out.print(n + " ");
		}
		System.out.println();//줄바꿈 처리
        
        for(int i = 0; i < numArr.length - 1; i++) { 
        	//배열크기 - 1 : 마지막 요소는 처리하지 않음
            min = i;
            for(int j = i + 1; j < numArr.length; j++) {
                if(numArr[min] > numArr[j]) {
                    min = j;
                }
            }
            temp = numArr[min];
            numArr[min] = numArr[i];
            numArr[i] = temp;
        }
        
        System.out.print("정렬 후 : ");
		for(int n : numArr) {
			System.out.print(n + " ");
		}
	}
}

최소값을 선택해 맨 앞 배열과 교환하여 배열하는 방법

 

 

 

 

 

import java.util.Scanner;

public class MoneyBook {

	public static void main(String[] args) {
		final int MAX = 2;
				
		String date[] = new String[MAX];
		int inMoney[] = new int[MAX];
		int outMoney[] = new int[MAX];
		String list[] = new String[MAX];
		int balance = 0;
		int totalInMoney = 0;
		int totalOutMoney = 0;
		
		int select = 0;
		
		Scanner scan = new Scanner(System.in);
		
		System.out.println("-- 가계부 프로그램 --");
			
			while(true) {
				System.out.println("------------------------");
				System.out.println("<< 메뉴 >>");
				System.out.println("1. 내역 등록 ");
				System.out.println("2. 전체 출력 ");
				System.out.println("3. 수입 출력 ");
				System.out.println("4. 지출 출력 ");
				System.out.println("5. 종료 ");
				System.out.print("선택> ");
				select = scan.nextInt();
				
				if(select == 5) {
					System.out.println("프로그램을 종료합니다.");
						break;}
				
				switch(select) {
					case 1:
						for(int i = 0; i < MAX; i++) {
							System.out.println("-------------------");
							scan.nextLine();//enter skip해줌							
							System.out.println("날짜 : ");
							date[i] = scan.nextLine();
							
							System.out.println("수입 금액 : ");
							inMoney[i] = scan.nextInt();	
							totalInMoney += inMoney[i];
							
							System.out.println("지출 금액 : ");
							outMoney[i] = scan.nextInt();
							totalOutMoney += outMoney[i];
							scan.nextLine();
							
							System.out.println("내역 : ");
							list[i] = scan.nextLine();

							System.out.println();
						}	
						break;
					case 2:
						System.out.println();
						for(int i = 0; i < MAX; i++) {
							System.out.println("--------------------------");
							System.out.println(" 날짜 : " + date[i]);
							System.out.printf(" 수입 : %,d원%n", inMoney[i]);
							System.out.printf(" 지출 : %,d원%n", outMoney[i]);
							System.out.println(" 내역 : " + list[i]);
							System.out.println();
						}//1~MAX까지의 내역이 전체 출력되야 하므로 배열로 받음

						balance = totalInMoney - totalOutMoney;
						System.out.println("--------------------------");
						System.out.printf(" 전체 수입 금액 : %,d원%n", totalInMoney);
						System.out.printf(" 전체 지출 금액 : %,d원%n", totalOutMoney);
						System.out.printf(" 전체 잔액 : %,d원%n", balance);
						break;
					case 3:
						System.out.println();
						for(int i = 0; i < MAX; i++) {
							System.out.println("--------------------------");
							System.out.println(" 날짜 : " + date[i]);
							System.out.printf(" 수입 : %,d원%n", inMoney[i]);
							System.out.println(" 내역 : " + list[i]);
							System.out.println();
						}

						System.out.printf(" 잔액 : %,d원%n", balance);
						System.out.printf(" 전체 수입 금액 : %,d원%n", totalInMoney);
						break;
					case 4:
						totalOutMoney = -(totalOutMoney);
						System.out.println();
						for(int i = 0; i < MAX; i++) {
							System.out.println("--------------------------");
							System.out.println(" 날짜 : " + date[i]);
							System.out.printf(" 지출 : %,d원%n", outMoney[i]);
							System.out.println(" 내역 : " + list[i]);
							System.out.println();
						}

						System.out.printf(" 잔액 : %,d원%n", balance);
						System.out.printf(" 전체 지출 금액 : %,d원%n", totalOutMoney);
						break;
					default://잘못된 메뉴 입력
						System.out.println("잘못 누르셨습니다.");
						break;						
				}
			}		
	}

}

- 사용한 변수

 1. 내역 등록 
 2. 수입 
 3. 지출 
 4. 잔액 
 5. 전체 수입 금액 
 6. 전체 지출 금액

 

- 실행 결과

1. 내역등록 선택시
2. 전체 내역 출력
3. 수입 내역 출력
4. 지출 내역 출력
5. 프로그램 종료

 

- 유의사항

한글 입력시 오류가 발생해서 영어로만 입력을 받는 프로그램이 되었다.

- 배열 예제(학생 관리 프로그램)

import java.util.Scanner;

public class StudentManager {
	
	static Scanner scan = new Scanner(System.in);

	public static void main(String[] args) {
		final int MAX = 1;
				
		String names[] = new String[MAX];
		String major[] = new String[MAX];
		String phone[] = new String[MAX];
		String sNumber[] = new String[MAX];
		float avg[] = new float[MAX];
		
		int select = 0;//메뉴 입력값 저장 변수
		
		Scanner scan = new Scanner(System.in);
		
		System.out.println("-- 학생 관리 프로그램 --");
		
		while(true) {
			System.out.println("<< 메뉴 >>");
			System.out.println("1. 정보 입력 ");// 입력 처리 메소드
			System.out.println("2. 정보 출력 ");// 출력 처리 메소드
			System.out.println("3. 종료 ");
			System.out.print("선택> ");
			select = scan.nextInt();		
			
			//먼저 처리할 메뉴 : 종료
			if(select == 3) {
				System.out.println("종료합니다.");
				break;
			}
			
			switch(select) {
			case 1://입력메뉴
				//서브 타이틀 출력 
				System.out.println("학생 등록");
				for(int i = 0; i < MAX; i++) {
					System.out.println("-------------------");
					scan.nextLine();//enter skip해줌
					System.out.print("이름 : ");
					names[i] = scan.nextLine();
					System.out.print("학과 : ");
					major[i] = scan.nextLine();
					System.out.print("연락처 : ");
					phone[i] = scan.nextLine();
					System.out.print("학번 : ");
					sNumber[i] = scan.nextLine();
					System.out.print("평균 : ");
					//avg[i] = scan.nextFloat();
					String fStr = scan.nextLine();
					avg[i] = Float.parseFloat(fStr);
				}
				break;
			case 2://출력메뉴
				System.out.println();
				for(int i = 0; i < MAX; i++) {
					System.out.println("-------------------");
					//scan.nextLine();//enter skip해줌
					System.out.print(" 이름 : " + names[i]);
					System.out.print(" 학과 : " + major[i]);
					System.out.print(" 연락처 : " + phone[i]);
					System.out.print(" 학번 : " + sNumber[i]);
					System.out.print(" 평균 : " + avg[i]);
				}
				break;
			default://잘못된 메뉴 입력
				System.out.println("잘못 누르셨습니다.");
				break;
			}
	}
}//main method
	private static int printMenu() {
		return 0;
	}
}//class

- 필요한 변수

1. 이름 2. 학과 3. 연락처 4. 학번 5. 평균

 

final : 더 이상 변경할 수 없다는 의미의 상수

final MAX 값을 하나만 바꿔줌으로써 다른 변수들도 다 변경되므로 상수를 사용한다.

 

select = 0 은 메뉴 입력값 저장 변수로 switch문에서 사용된다.

 

- 문자열 -> 실수 변환하는 방법

avg[i] = (데이터 자료형).parseFlat(fStr);

 

- Enter 오류 해결 방법

키보드에는 잠깐의 시간 텀을 둬서 임시로 저장하는 버퍼가 있다.

숫자형만 취급하므로 a~z, A~Z는 취급을 하지 않는다. enter가 눌리면 입력이 끝났다고 인지를 한다.

nextLine에서 문자열을 받는 것들은 enter도 문자라고 인식을 한다.

scan에서 enter가 들어오면 입력이 끝났다고 인식을 하기 때문에 오류가 발생한다.

숫자를 받고 문자를 받게되면 enter가 남아서 입력처리가 되지 않는다.

따라서 enter를 없대면 문제가 해결된다.

해결 방법으로는 두가지가 있다.

1) scan.nextLine();

2) 문자열(String)로만 전부다 입력 받음, 숫자일 경우에는 변환

public class MethodTest {

	//여기에 메소드 작성

	public static void main(String[] args) {//()가 있으면 파라미터가 있는 메소드
		// TODO Auto-generated method stub
		//메소드 내부에 메소드 X

	}// main method

	//여기에 메소드 작성
}

- Method

하나 또는 여러 가지 기능을 묶어서 독립적으로 사용할 수 있는 프로그램의 구성단위

입력값(파라미터)을 넣어주면 해당 기능을 처리하고, 출력 값을 되돌려 준다.(반환한다.)

 

- Method의 종류

1. 파라미터와 반환 값이 두 가지 전부 다 존재하는 메서드

2. 파라미터는 존재하나 반환 값이 없는 메서드

3. 파라미터는 없으나 반환 값은 존재하는 메서드

4. 둘 다 없는 메서드

 

- Method 작성 형식

자료형 메서드 이름(매개 변수 1, 매개 변수 2,...){... }

 

- Method 이름의 특징

특수문자는 _와 $만 사용 가능, 2개 이상 단어 조합 시 첫 번째 글자는 대문자

클래스 이름은 글자만 대문자, 상수은 모든 글자가 대문자로 이루어진다.

 

메서드는 이름을 마음대로 작성할 수 있다.

하지만 main 메소드는 마음대로 이름을 작성할 수 없다.

main 메소드는 무조건 한 프로그램에 반드시 한 개만 있어야 한다.

똑같은 이름을 사용하면 안 된다.

 

- 사칙연산 계산기 예제

int rs = add(1, 2);
System.out.println("1 + 2 = " + rs);
System.out.println("3 + 4 = " + add(3, 4));
int a1, a2;
a1 = scan.nextInt();
a2 = scan.nextInt();
System.out.println(a1 + " + " + a2 + " = " + add(a1, a2));
//변수가 통째로 전달되는 것이 아닌 안에 있는 정보만 전달됨

두 개의 값을 입력받는 메서드이다.

결과를 반환하는 메서드이다.

메서드 이름 앞에 붙이는 자료형을 반환되는(결과) 값의 자료형을 붙인다. => 반환형

1. 파라미터 O, 반환 값 O

public static int add(int a, int b) {
	int c, d;
	int result = a + b;
	return result;
}

결과 값을 줄 때 정수 값이 아닌 실수

 

2. 파라미터 O, 반환 값 X

	public static void sub(int a, int b) {
		int result = a - b;
		System.out.println(a + " - " + b + " = " + result);
	}
sub(a1, a2);

형식에 맞춰서 사용해야 함. return이 없는 경우에는 void 사용

 

3. 파라미터 X, 반환 값 O

public static int mul() {
	int a = scan.nextInt();
	int b = scan.nextInt();
	int result = a * b;
	return result;
}
rs = mul();

 

4. 파라미터 X, 반환값 X

public static void div() {
	int a = scan.nextInt();
	int b = scan.nextInt();
	int result = a / b;
	System.out.println(a + " / " + b + " = " + result);
}
div();

입력 출력 모두 생성한 뒤 받는다.

 

 

 

*파라미터란.

사용자가 원하는 방식으로 자료가 처리되도록 하기 위하여 명령어를 입력할  추가하거나 변경하는 수치 정보.

- 배열(Array)

int score[] = new int[n];

n개짜리 배열을 만드는 방법. 

0~(n-1)까지의 배열이 생성된다. 배열의 공간을 사용한다. 배열의 공간에 대입해주지 않으면 0으로 채워져있다.

선언은 한번에 여러 개로 할 수 있지만 사용은 개별적으로 할 수 있다.

 

- 배열 예시

import java.util.Scanner;

public class ArrayTest01 {

	public static void main(String[] args) {
		
		int score[] = new int[5];
		
		score[0] = 80;
		score[1] = 93; 
		
		System.out.println(score[0]);
		System.out.println(score[1]);
		
		System.out.println("성적 입력 프로그램");
		
		Scanner scan = new Scanner(System.in);
		
		for(int i = 0; i < 5 ; i++) {
			System.out.print((i+1) + "번째 학생 성적 : ");
			score[i] = scan.nextInt();
		}
		
		int sum = 0;
		for(int j = 0; j < 5 ; j++) {
			sum += score[j];
		}
		
		double avg = 0;
		avg = (double)sum/5;
		
		
		System.out.println();
		System.out.println("총점은 " + sum);
		System.out.println("평균은 " + avg);
	}
}

n개의 배열을 생성할 경우 0~(n-1)개가 생성된다.
그러므로 배열에 변수를 넣을 경우 [0]부터 생각해주어야한다.
특정한 배열에만 변수를 넣었을 경우에는 변수를 넣어주지 않은 배열은 0으로 남아있다.

 

- 향상된 for문 (읽기전용)

for(int s : score) {
			sum += s;
		}

s에 score을 대입해서 처음부터 끝까지 sum += s를 실행한다.

변수 s 자체를 없앴다가 다시 생성하는 과정을 반복하여 for문 안에서만 사용함.

score에 있는 값을 s에 임시저장하는 목적으로 사용한다.

데이터가 없을 때까지 배열의 마지막까지 내부적으로 작업을 처리한다.

if문을 사용해 중간에 제어하지 않는 이상 처음부터 끝까지 실행한다.

 

- 프로그램의 구성요소

1. 입력 : 사용자로부터 값을 입력받는다.

2. 연산 : 값을 처리한다.

3. 출력 : 값을 출력한다.

 

- 프로그램 코딩의 구조

1. 일괄처리 : 위에서부터 아래로 순서대로 한줄씩 순서대로 처리한다.

2. 반복처리 : 특정 조건에 따라 반복한다.

=>모든 프로그램은 사용자의 종료 명령이 없다면 정해진 순서의 명령 문장을 순서대로 반복한다.

 

- 디버깅

프로그램이 잘 돌고있는지 확인한다.

내부적으로 연산이 잘 수행되고 있는지 확인한 후 최종적인 결과가 잘 나올 수 있도록 최종적으로 수정해서 보완하는 과정이다.

 

- 디버깅 단축키

F11 디버깅을 실행하는 단축키
F6 브레이크 포인트를 걸어준 다음 한줄씩 실행
F8 다음 브레이크 포인트까지 넘어감

 

- while문

import java.util.Scanner;

public class InfiniteLoop01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		int menu = 0;
		
		System.out.println("메뉴 출력");
		
		while(true) {
			System.out.println("1. 입력하기");
			System.out.println("2. 불러오기");
			System.out.println("3. 저장하기");
			System.out.println("4. 출력하기");
			System.out.println("5. 종료하기");
			System.out.print("입력 > ");
			menu = scan.nextInt();
			
			if(menu == 5) {
				break;//반복문 종료
			}
			
		switch(menu) {
		case 1:
			System.out.println("입력하기 처리");
			break;
		case 2:
			System.out.println("불러오기 처리");
			break;
		case 3:
			System.out.println("저장하기 처리");
			break;
		case 4:
			System.out.println("출력하기 처리");
			break;	
		default:
			System.out.println("입력오류!!");
			break;	
			}
		}		
	}//main 끝
}//class 끝

- 코드 설명

for( ; ; ) : for문의 기본 형식은 초기화식 ; 조건식 ; 증가식; 이다.

            하지만 빈칸으로 두면 조건식이 없으므로 항상 참이기 때문에 반복문이 무한 반복된다.
while(true) : 조건이 항상 true이기때문에 무한 반복된다.

break : while문, for문에서는 반복문을 종료하는 의미로 사용된다. 하지만 if문에서는 의미가 없으므로 사용하지 않는다.

         cf.switch 안의 break는 switch문만 종료하게 되는거라 반복문은 계속 진행된다.
case 5: 가 없는 이유 : 5번이 switch 안에 있으면 switch문을 한번 더 실행해야 한다. 프로그램처리를 진행할 때 switch문을 추가적으로 실행해야한다. 하지만 5번을 먼저 처리하면 switch문을 처리할 필요가 없기 때문에 먼저 처리해준다.

 

- while문과 for문 비교

import java.util.*;

public class OperationTest05 {

	public static void main(String[] args) {
		int i = 1;
		int sum = 0;
		
		
		while(i <= 100) {
			sum += i;
			i++;			
		}
		
		System.out.printf("1~100까지 총합은 [%d]%n", sum);
		
		
		int sum2 = 0;
		for(int j = 1; j <= 100; j++) {
			sum2 += j;
		}
		System.out.printf("1~100까지 총합은 [%d]%n", sum2);
		
		
		
	}

}

while문은 조건만 제시하고, while문 안에 연산과 증가식을 포함한다.
for문은 초기식, 조건식, 증가식을 제시한 뒤 연산을 포함한다.

작성 방법이 다르지만 동일한 내용의 반복문이며 같은 결과가 나온다.

 

- while문과 for문 구구단 예시 비교

public class OperationTest04{

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("구구단");
		
		for(int i = 1; i < 10; i++) {
			for(int j = 2; j < 10; j++) {
				System.out.printf("%d*%d=%2d ", j, i, i*j);
			}
			System.out.println();
		}//for문
		
		int i = 0;
		while(i<9) {
			i++;
			int j = 1;
			while(j<9) {
				j++;
				System.out.printf("%d * %d = %2d ", j, i, i*j);
			}
			System.out.println();	
		}//while문 끝
	}
}

결과값

조건이 맞을 경우 i와 j에 1을 더해준 뒤 구구단을 실행하기 때문에 초기값을 0으로 설정해주었다.

 

- while문과 do, while문 비교

   -1이 입력될 때까지 반복적으로 점수를 입력받아서 평균을 출력하는 프로그램

import java.util.Scanner;

public class OperationTest06 {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		int inNum = 0, total = 0, cnt = 0;
		double avg = 0.0f;
		
		cnt = -1;
		
        //while문
        		inNum = scan.nextInt();		
		while(inNum != -1) {
				total += inNum;
				inNum = scan.nextInt();
				cnt++;
		}        
        
        
	//do while문
        do {
			total += inNum;
			cnt++;
			inNum = scan.nextInt();
		}while(inNum != -1);
		
		avg = (double)total/cnt;
		System.out.println(cnt + "명 평균은" + avg);
		System.out.printf("%d 명 평균은 %f", cnt, avg);
	}
}
while문 조건 먼저 확인 => 연산 실행 반복
do while문 먼저 연산을 실행(do) => 조건 확인 반복

 

- 프로그램 순서

1. 스캐너 만들기

2. 사용할 변수 만들기

   점수 입력용 변수 score

   평균 저장 변수 avg

   총점 저장 변수 totalScore

   카운트 변수(입력 횟수 저장 변수) cnt

3. 점수 입력

   -1이라면/아니라면

   -1이라면 총점을 카운트변수 나눗셈하여 평균 계산.

   -1이 아니라면 총점에 입력한 점수 더하기.(반복)

   while은 조건을 따지고 실해. do while은 먼저하고, 조건을 따지는 것

4. 평균 출력

   정수 연산 => 실수 연산이므로 형변환을 해줘야한다. 

   형변환을 하지않으면 오류가 발생한다.

 

- 주의사항

평균 출력에서 System.out.printf("%d 명 평균은 %d", cnt, avg);로 하면 오류가 발생함

=> double은 %d를 사용하면 안되고, %f를 사용해야 한다.

 

 

 

import java.util.Random;
import java.util.Scanner;

public class Upndown {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		
		Random rand = new Random();
		int num = rand.nextInt(100);//0~99 중에서 랜덤으로 선언됨
		num++; //1~100까지의 값을 사용하고 싶으므로 num에 1을 더해줌
		
        System.out.println("입력해주세요.");
		int i = scan.nextInt();
		System.out.printf("입력 > %d%n", i);
        
		
		for(int j = 1; j < 10; j++) {//최대 10번까지 가능하므로 for문을 실행시킬 변수 j 선언해줌
            if(i != num) {//scan 입력한 값과 랜덤 num이 다를 경우
                if(num > i) {//입력한 값이 작을 경우
                    System.out.println("UP!");
                    i = scan.nextInt();//UP! 출력과 scan 값을 다시 입력 받음
                    System.out.printf("입력 > %d%n", i);
                }
                else if(num < i) {//입력한 값이 클 경우
                    System.out.println("DOWN!");
                    i = scan.nextInt();//DOWN! 출력과 scan 값을 다시 입력 받음
                    System.out.printf("입력 > %d%n", i);
                }
                if(j == 9) {//j의 최대값
                    System.out.printf("실패! 정답 %d%n", num);
                }
			}
            else if(i == num){//scan 입력 값이 랜덤 num과 동일한 경우
                System.out.printf("시도 횟수 %d번 성공!", j);	//시도횟수를 알려주기 위해 변수 j 사용
                break;
                }	
		}	
	}
}

-유의사항

1. 처음에는 시도 횟수를 확인해 주기 위해서 cnt 변수를 추가하려고 했다. 하지만 for문에서 사용하는 j 변수도 계속 증가하기 때문에 결국 시도 횟수와 동일하다. 그러므로 j 변수를 사용하면 되므로 굳이 cnt 변수를 추가할 필요가 없다. 

 

2. 10번 시도했을 때 "실패! 정답 num" 출력하는 if문에서 j == 9인 이유

    1) for문에서 조건식이 j < 10이기때문에 9까지만 for문이 돌기 때문에 j 는 10 이상이 될 수 없다.

    2) i 값을 10번 scan 받는데 9까지인 이유는 제일 먼저 scan 받는 건 for문이 시작되기 전에 입력받기 때문이다.

       for문 시작 전의 1번과 for문 안에서의 9번을 합하면 총 10번 도전하게된다.

 

- 수업시간에 한 코드

import java.util.*;

public class UpAndDown {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		Random rand = new Random();
		
		
        boolean success = false;
		
		int num = rand.nextInt(100) + 1;
		
		int inNum = 0;
		
		for(int i = 1; i <= 10; i++) {
			System.out.print("입력 > ");
			inNum = scan.nextInt();
			
			if(num == inNum) {
				System.out.printf("시도 횟수 [%d]번 성공", i);
				success = true;
				break;
			}else if(num > inNum) {
				System.out.println("UP!");
			}else if(num < inNum) {
				System.out.println("DOWN!");
			}
			
		}
		if(success == false) {
			System.out.println("실패! 정답" + num);			
		}
	}//main 끝

}//클래스 끝

boolean으로 success 값을 주어 성공과 실패를 판단한다.
scan 입력 값을 for문 안에서부터 받기 때문에 1부터 시작해서 10이하일 때까지 반복한다.

import java.util.Scanner;

public class Calendar {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);

		int allDay = 0, startDay = 0, endDay = 0;
		int year = 0, month = 0;

		System.out.println("년도를 입력하세요. ");
		year = scan.nextInt();

		System.out.println("월을 입력하세요. ");
		month = scan.nextInt();

		for (int i = 1; i < year; i++) {//입력한 년도보다 작년까지의 합이 필요함으로 i < year로 사용
			allDay += 365;
			//1년 지날때마다 365씩 더해줌
			if ((((i % 4) == 0) && (i % 100) != 0) || ((i % 400) == 0)) {
				//if문에서 year가 아닌 i를 써주는 이유는 for문에서 1년부터 입력한 year까지의 합을 구해주는 과정이기 때문.
				//i가 아닌 year를 사용할 경우 1~year까지의 윤년 확인이 아닌 입력받은 year의 윤년 유무만 확인하게 된다.
				allDay++;
				//윤년인 경우 2월이 28일에서 29일이 되어 하루가 더 증가하므로 1씩 더해줌
			}
		}

		for (int j = 1; j < month; j++) {//입력한 거보다 이전 달까지의 합이 필요하므로 j < month를 사용
			if ((j == 4) || (j == 6) || (j == 9) || (j == 11)) {//30일까지 있는 월들의 합
				allDay += 30;
			} else if (j == 2) {//29일까지인 2월 찾기
				if ((((year % 4) == 0) && (year % 100) != 0) || ((year % 400) == 0)) {
					//j는 월을 의미하기 때문에 윤년을 확인하기 위해서는 입력한 year으로 비교해야한다.
					allDay += 29;
				} else {
					allDay += 28;
				}
			} else {//2, 4, 6, 9, 11 이외의 월은 31일까지
				allDay += 31;
			}
		}

		startDay = allDay % 7;//해당 월의 시작 날짜를 알아주기 위해 더해준 allDay를 7로 나누어 나머지 값을 startDay에 대입

		
		
		//월의 끝나는 날짜 구하기(28, 29, 30, 31)
		if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
			endDay = 30;
		} else if (month == 2) {
			if ((((month % 4) == 0) && (month % 100) != 0) || ((month % 400) == 0)) {
				endDay = 29;
			} else {
				endDay = 28;
			}
		} else {
			endDay = 31;
		}
		
		
		
		
		System.out.printf("%d년\t\t\t\t\t\t%d월%n", year, month);
		System.out.printf("===============================================%n");
		System.out.printf("일\t월\t화\t수\t목\t금\t토%n");
		System.out.printf("===============================================%n");
		
		
		
		int cnt = 0;
		//7일마다 줄 바꿔주기 위해서 cnt 변수를 0으로 초기화해줌
		
		
		for(int l = 0; l <= startDay; l++) {
			if(startDay == 6)//startDay가 6이면 공백을 주지 않아도 되므로 break을 사용해서 for문을 빠져나온다.
				break;
			System.out.print("\t");
			cnt++;
		}
				for(int m = 1; m <= endDay; m++) {//1부터 endDay까지 숫자를 입력해줌
					System.out.printf("%2d", m);
					cnt++;
					if(cnt % 7 == 0) {//cnt가 7번 입력됐을 때 줄을 바꿔줌
						System.out.println();
					}
					else {
						System.out.printf("\t");//cnt가 7번 입력되지않았을 때는 간격을 넣어줌
				}
		}
	}
}

-실행 결과

-변수설명

allDay : 1년 1월 1일부터 입력한 날짜의 지난 달까지의 날짜들의 합
           ex. 입력한 날이 2020년 3월이라면 1년 1월 1일 ~ 2020년 2월 29일까지의 합

startDay : 해당 월에서 날짜가 시작하는 요일 구하기 위한 변수
endDay : 해당 월의 끝나는 날짜

year : scan 받는 년도

month : scan 받는 월

 

+ Recent posts