초보의 입장에서보면 무자비 하게 등장하는 term들은 프로그래밍의 세계에 더욱 높은 장벽을 쌓아준다.
아직도 객체, 메서드 기타 등등의 단어는 아직도 이해하지 못했고.
지금은 integer를 많이 쓰며 변수, 값 이라는 단어 정도 이해한 상태다.
이렇게 아무것도 모르는 초보는 선생님이 써주는 코드를 보고 그냥 무지성으로 치는 수준으로만 따라 하는데
가끔씩 이런 구조적 설명 너무나 마른땅의 단비 같다는것... ㅎ
여튼 오늘은 변수의 범위를 배웠다.
변수의 범위는 속해있는 {중괄호} 속이다.
정확히 말해,
the scope of variables is limited to the first pair of curly brackets that encloses them
변수를 감싸는 첫 {중괄호} 속
좌측의 경우는 value 값이 출력될 수 있지만, 우측의 경우는 에러표시가 뜨고 value 값은 출력되지 않는다.


이런 예시도 있다.
String input을 {중괄호} 밖에서 선언하여, do 와 while 모두가 String input을 받을 수 있도록 한다.


오늘 연습한 코드
import java.util.Scanner;
public class App {
public static void main(String[] args) {
{
int value = 0;
System.out.println(value);
}
// Error - out of the scope!
// System.out.println(value);
Scanner scanner = new Scanner(System.in);
for(int i=0; i<4; i++) {
System.out.println(i);
}
// 여기도 for 문을 못받음
// System.out.println(i);
String input = null;
do {
System.out.println("type 'quit!' if you want me to shut up.");
input = scanner.nextLine();
} while (!input.equals("quit!"));
scanner.close();
}
}
그 결과값

선생님의 당부말씀>> 이게 진짜임
make sure you understand how to write a do while loop in such a way that you can both get user input and refer to it in the loop condition becuase that might come in handy.
그럼 바로 지피티에게 ㄱ
해서 만든 코드는 아래와 같고.
import java.util.Scanner;
public class practice_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String userInput = null;
do {
System.out.println("원하는 숫자 입력 (종료하려면 0입력) >");
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
int number = Integer.parseInt(userInput);
System.out.println("입력하신 숫자는 " + number + " 맞쥬?");
} else {
System.out.println("숫자만 입력해 주세유... ");
}
} while (userInput.equals("o"));
System.out.println("시스템이 종료합니다.");
scanner.close();
}
}
아래는 출력물

일단 오늘 많은것을 할 여유가 없으므로
해피코딩
'콤퓨타 > Programming) 왕초보 자바' 카테고리의 다른 글
| 28. (Loops and Conditions) Flags (4) | 2025.08.19 |
|---|---|
| 27. (Loops and Conditions) Checking Password with Do-While (feat. 챗지피티 활용 위기관리) (6) | 2025.08.17 |
| 26. (Loops and Conditions) Not - Not equal Do While Loop (1) | 2025.08.14 |
| (번외) do while 연습 (feat. 증감연산자) (1) | 2025.08.11 |
| 25. (Loops and Conditions) Do While Loop (1) | 2025.08.11 |