04_코드는 한 줄씩 차례대로 실행된다

Jiyoon.lee·2023년 11월 18일
0

Java_inflearn

목록 보기
4/25

1. 이름, 이메일, 성별 출력하기

1) MyProfile 클래스 작성

public class MyProfile {
    public static void main(String[] args) {
        System.out.println("이지윤");
        System.out.println("wls8152296@naver.com");
        System.out.println("여자");
    }
}

2) 실행 결과

이지윤
wls8152296@naver.com
여자

2. main()메소드 안의 내용은 차례대로 실행된다.

  • main()메소드 안의 내용이 한 줄씩 한 줄씩 실행된다.

3. println()메소드를 print()로 바꿔보기

public class MyProfile {
    public static void main(String[] args) {
        System.out.print("이지윤");
        System.out.print("wls8152296@naver.com");
        System.out.print("여자");
    }
}

실행 결과 :

이지윤wls8152296@naver.com여자

*out은 printStream

4. print()메소드는 줄바꿈을 하지 않는다.

  • println()메소드는 괄호 안의 내용을 출력하고 줄바꿈을 하지만, print()메소드는 괄호 안의 내용만 출력한다. (줄바꿈을 하지 않음)
  • System.out.println();은 아무것도 출력하지 않고 줄바꿈만 한다.

5. 연습 문제

  • 다음과 같은 결과를 출력하는 Rectangle클래스를 작성한다. (너비가 별 10개, 높이가 별 10개인 사각형)
public class Rectangle {
    public static void main(String[] args) {
        System.out.println("**********");
        System.out.println("**********");
        System.out.println("**********");
        System.out.println("**********");
        System.out.println("**********");
        System.out.println("**********");
        System.out.println("**********");
        System.out.println("**********");
        System.out.println("**********");
        System.out.println("**********");
    }
}

6. 높이가 200인 사각형을 출력하려면?

  • 만약 높이가 10,000인 사각형을 출력하라고 문제가 바뀐다면?
  • 컴퓨터가 가장 잘하는 일은 반복하는 일

7. while반복문을 이용해 높이가 10인 사각형 출력하기

public class Rectangle2 {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 10) {
            System.out.println("**********");
            i = i + 1;    // i++;
        }
    }
}

8. while 반복문

  • main메소드 안의 내용은 한 줄씩 실행해 나간다. JVM이 한 줄씩 읽어나가면서 해석하고 실행한다.
  • 정수 타입(type) 변수 i에 1을 저장한다. 자바 프로그래밍에서 =은 같다라는 의미가 아니라, 우측의 값을 좌측에 "저장"한다는 의미이다.
    int i = 1;
  • while(i <= 10) {...}은 i가 10보다 작거나 같을 때까지 중괄호 안의 내용을 반복하라는 의미이다. 중괄호 부분은 블록이라고 한다. 즉 i가 10보다 크다면 반복하지 말라는 말이다.
  • 괄호 안의 i = i + 1은 i에 저장된 값에 1을 더한 후 그 값을 다시 i에 저장하라는 뜻이다.
while (i <= 10) {
            ......
            i = i + 1;    // i++;
        }
  • 즉, 아래의 코드는 i는 1부터 시작해서 while블록 안의 내용을 반복할 때마다 i를 1씩 증가시키라는 의미이다.
  • 이때, i가 10보다 작거나 같을 경우는 계속 반복하게 된다. 어느 시점에 i가 11이 되는 경우가 발생하는데, 이때는 while블록을 종료하게 되고, 그 다음 줄을 실행하게 된다.
        int i = 1;
        while (i <= 10) {
            System.out.println("**********");
            i = i + 1;    // i++;
        }

9. 연습 문제

  • 높이가 1000인 사각형을 출력하자.
public class Rectangle3 {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 1000) {
            System.out.println("**********");
            i = i + 1;    // i++;
        }
    }
}

0개의 댓글