본문 바로가기

콤퓨타/Programming) 왕초보 자바

27. (Loops and Conditions) Variable Scope

 

 

 

 

 

초보의 입장에서보면 무자비 하게 등장하는 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을 받을 수 있도록 한다. 

(좌) do 안에만 String input 이 있음 (우) do 밖에 String input이 있어서 while에게도 해당 선언이 반영될 수 있음

 

 

 

오늘 연습한 코드 

 

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();

	}

}

아래는 출력물

 

일단 오늘 많은것을 할 여유가 없으므로 

해피코딩