[JAVA] 기초 문법 연습 문제 - 입출력, 연산자, 조건문, 반복문, 배열

이연우·2025년 7월 7일

TIL

목록 보기
1/100

> JAVA 기초 문법 및 GitHub 명령어

JAVA 기초 문법 다지기

  • Chapter 1-4. 변수
    → 변수: 데이터를 컴퓨터에 저장하기 위한 공간
                [자료형] [변수 이름] [세미콜론]
자료형종류범위바이트비트
boolean논리형true/false18
char문자형0~65,535 유니코드 값216
byte정수형-128~12718
short정수형-32,768~32,767216
int정수형-2,147,483,648 ~ 2,147,483,647432
long정수형-9,233,372,036,854,775,808 ~ 9,233,372,036,854,775,807864
float실수형약 소수점 6~7자리까지432
double실수형약 소수점 15~17자리까지864

  • Chapter 1-9. 배열
    → 배열: 비슷한 주제의 데이터를 그룹으로 묶어서 표현하는 방법
         → 관련된 데이터를 편하게 관리하기 위해 사용됨

       → new 키워드를 사용하여 배열 선언
           ⇢ 자료형[ ] 변수 이름 = new 자료형[배열의 길이];

       → 배열의 요소에 접근하려면 "인덱스(index)" 이용

  • Chapter 1-10. 메소드
    → 메소드(method): 함수, 기능이라고도 불리며 작업을 표현하는 방법
    → 여러 개의 작은 명령문을 한곳에 모아 사용하는 단위, 호출부/선언부로 나누어짐

-> 메소드 구조

public class 클래스 이름 {

		[반환 자료형] [메소드 이름] (매개변수...) {
				작업 명령문들...
		}
}

   ⇢ 호출부: 메소드를 사용하는 곳(ex. Main.java)
   ⇢ 선언부: 메소드가 정의되어 있는 곳

- 반환 데이터가 없을 때는 반환 자료형 위치에 "void" 선언

public class Calculator {
		
		// ✅ void로 반환 데이터가 없음을 표시
		void sum(int value1, value2) { 
				int result = value1 + value2;
				System.out.println("계산 결과는 " + result + "입니다.");
		}
}

public class Main {

		public static void main(String[] args {
				Calculator calculator = new Calculator();
				calculator.sum(1, 2); // ✅ 반환 데이터가 없기 때문에 받아서 처리하지 않아도 됨
		}
}

- 반환 값이 있을 때는 "return" 선언

public class Calculator {

		int sum(int value1, value2) {
				int result = value1 + value2;
				return result; // ✅ result가 반환됨
		}
}

public class Main {

		public static void main(String[] args {
				Calculator calculator = new Calculator();
				int result = calculator.sum(1, 2); // ✅ 반환된 데이터를 result 변수에 담아 사용
				System.out.println("계산 결과는 " + result + "입니다.");
		}
}

GitHub 명령어 숙지

Git 버전 확인

  • git --version

새로운 Git 저장소 초기화

  • git init

유저 이메일, 이름 입력

  • git confing --global user.email "email@gmail.com"
  • git confing --global user.name "nickname"

파일 현재 상태 기록

  • git add 파일명
  • git commit -m '메시지'

commit 기록 확인

  • git log --all --oneline
  • git log --all --oneline --graph

git 브랜치 생성

  • git branch <브랜치 이름>

git 브랜치 이동

  • git switch <브랜치 이름>

git 브랜치 병합

  • main/master 브랜치로 이동한 뒤 git merge <브랜치 이름>

원격 저장소로부터 복제

  • git clone <원격 저장소 주소>


> Chapter 1 - 자바 기초 문법 다지기


Chapter 1-5. 입출력

- 이름과 나이 입력받아 출력하는 프로그램

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("이름을 입력하세요: ");
        String name =  sc.nextLine();

        System.out.print("나이를 입력하세요: ");
        int age = sc.nextInt();

        System.out.println("\n> 출력 결과");
        System.out.println("이름: " + name);
        System.out.println("나이: " + age);

        sc.close();
    }
}

출력 결과

이름을 입력하세요: Suu
나이를 입력하세요: 20

> 출력 결과
이름: Suu
나이: 20

Chapter 1-6. 연산자

1. 산술 연산자 문제

  • 두 개의 정수 a와 b가 주어졌을 때의 두 수의 합, 차, 곱, 나누기와 나머지 연산 결과 출력
public class Main {
    public static void main(String[] args) {
        int a = 15;
        int b = 4;

        System.out.println("덧셈 결과: " + (a+b));
        System.out.println("뺄셈 결과: " + (a-b));
        System.out.println("곱셈 결과: " + (a*b));
        System.out.println("나눗셈 결과: " + (a/b));
        System.out.println("나머지 결과: " + (a%b));
    }
}

출력 결과

덧셈 결과: 19
뺄셈 결과: 11
곱셈 결과: 60
나눗셈 결과: 3
나머지 결과: 3

2. 비교 연산자 문제

  • 두 개의 정수 x와 y가 주어졌을 때의 크기 비교 출력
public class Main {
    public static void main(String[] args) {
        int x = 4;
        int y = 7;

        boolean isBig = x > y;
        boolean isSmall = x < y;
        boolean isSame = x == y;
        boolean isDiff = x != y;

        System.out.println("x가 y보다 큰가? " + isBig);
        System.out.println("x가 y보다 작은가? " + isSmall);
        System.out.println("x가 y가 같은가? " + isSame);
        System.out.println("x가 y가 다른가? " + isDiff);
    }
}

출력 결과

x가 y보다 큰가? false
x가 y보다 작은가? true
x가 y가 같은가? false
x가 y가 다른가? true
  • 입력한 두 개의 문자열 같은지 비교하여 출력
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("첫 번째 문자열을 입력하세요: ");
        String input1 = sc.nextLine();

        System.out.print("두 번째 문자열을 입력하세요: ");
        String input2 = sc.nextLine();

        // 문자열은 .equals() 함수 사용
        boolean result = input1.equals(input2);

        System.out.println("두 문자열이 같은가요? " + result);

        sc.close();
    }
}

출력 결과

첫 번째 문자열을 입력하세요: Hello java
두 번째 문자열을 입력하세요: hello Java
두 문자열이 같은가요? false

Chapter 1-7. 조건문

- 신호등 안내 메시지 프로그램

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while(true) {
            System.out.print("신호등 색상을 입력하세요(초록불, 노란불, 빨간불): ");
            String color = sc.nextLine().trim();

            if (color.equals("초록불")) {
                System.out.println("건너세요!");
            }
            else if (color.equals("노란불")) {
                System.out.println("주의하세요!");
            }
            else if (color.equals("빨간불")) {
                System.out.println("멈추세요!");
            }
            else {
                System.out.println("잘못된 입력입니다.");
                break;
            }
        }

        sc.close();
    }
}

출력 결과

신호등 색상을 입력하세요(초록불, 노란불, 빨간불): 초록불
건너세요!
신호등 색상을 입력하세요(초록불, 노란불, 빨간불): 노란불
주의하세요!
신호등 색상을 입력하세요(초록불, 노란불, 빨간불): 빨간불
멈추세요!
신호등 색상을 입력하세요(초록불, 노란불, 빨간불): 파란불
잘못된 입력입니다.

Chapter 1-8. 반복문

1. 입력한 숫자의 구구단 출력

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("출력할 구구단 단수를 입력하세요(2~9): ");
        int num =  sc.nextInt();

        System.out.println("==== " + num + "단 ====");
        for (int i = 1; i <= 9; i++) {
            System.out.println(num + " x " + i + " = " + (num * i));
        }

        sc.close();
    }
}

출력 결과

출력할 구구단 단수를 입력하세요(2~9): 4
==== 4====
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36

2. 2단부터 9단까지 구구단 전체 출력(중첩 for문)

public class Main {
    public static void main(String[] args) {
        for(int i = 2; i <= 9; i++) {
            System.out.println("\n==== " + i + "단 ====");
            for(int j = 1; j <= 9; j++) {
                System.out.println(i + " x " + j + " = " + (i * j));
            }
        }
    }
}

출력 결과

==== 2====
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18

...

==== 9====
9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81

Chapter 1-9. 배열

1. 1차원 배열에서 짝수만 출력

public class Main {
    public static void main(String[] args) {
        int[] arr = {3, 4, 7, 10, 15, 20};

        System.out.print("짝수: ");
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0) {
                System.out.print(arr[i] + " ");
            }
        }
    }
}

출력 결과

짝수: 4 10 20 

2. 2차원 배열의 누적합 출력

public class Main {
    public static void main(String[] args) {
        int[] arr = {2, 5, 8};
        int sum = 0;
        
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }

        System.out.println("누적합: " + sum);
    }
}

출력 결과

누적합: 15

3. 2차원 배열에서 true의 좌표(x, y) 찾기

public class Main {
    public static void main(String[] args) {
        boolean[][] board = {
                {true, false},
                {false, true}
        };

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == true) {
                    System.out.println("true 위치: (" + i + "," + j + ")");
                }
            }
        }
    }
}

출력 결과

true 위치: (0,0)
true 위치: (1,1)

참고 - https://codingapple.com/course/git-and-github/

0개의 댓글