1. 브레이크문 위치에 따른 차이
for(int i=0; fscan.hasNext(); i++) {
String word = fscan.next(); //next는 문자열의 공백을 기준으로 한 단어 한 문자를 읽는다.
int kor = Integer.parseInt(word); //word의 데이터 값이 문자열이기 때문에 String -> Int로 바꾸는 Integer.parseInt()를 사용한다.
if(i>=5)
break;
System.out.println(kor);
if(i>=4)
break;
}
System.out.println(kor)을 기준으로 앞선 break문은 쓰면 뒤의 break문에 비해 1번 더 반복한다는 단점이 있다. 반면 뒤의 break문은 1번 더 반복되어 성능면에서 좋다. 하지만 뒤의 break문은 앞선 break문 보다 직관성이 떨어진다. 앞선 break문은 인간의 사고로 이해하기 쉬운반면, 뒤의 break문은 컴퓨터가 사고 하는 방식에 가깝다. 코드는 인간이 작성하기 한번 더 반복하더라도 인간의 사고를 따라가는 앞선 break문을 추천한다.
얼마나 직관적인가? 얼마나 효율적인가? 이 기준으로 break문의 위치를 잘 생각하자.
2.break VS continue
2.1 문제1) 파일에서 성적을 5번째 '까지'만 읽어서 다음처럼 화면에 출력하시오
30, 49, 38, 49, 50
public class breakAndcontinue {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("res/exam.list");
Scanner fscan = new Scanner(fis);
int index = 0; // while문 횟수 제한을 위해 인덱스 변수를 선언한다.
while(fscan.hasNext()) {
String word = fscan.next(); //next는 문자열의 공백을 기준으로 한 단어 한 문자를 읽는다.
int kor = Integer.parseInt(word);//word의 데이터 값이 문자열이기 때문에 String -> Int로 바꾸는 Integer.parseInt()를 사용한다.
if(index==5)
break;
index++;
System.out.printf("%d,",kor);
}
2.2 문제2) 파일에서 성적을 5번째 '이후'의 값을 읽어들여라
public class breakAndcontinue {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("res/exam.list");
Scanner fscan = new Scanner(fis);
for(int i=0; fscan.hasNext(); i++) {
String word = fscan.next();
int kor = Integer.parseInt(word);
if (i<4)
continue;
System.out.printf("%d,", kor);
}
}
3.상태변화
반복문의 문제를 만날 때 '상태변화'의 개념을 잘 이해해야한다. 상태변화란 반복문이 시행되는 동안 특정 상태로 변화되면 결과가 바뀌는 걸 말한다. 다음 예시들을 통해 '상태변화'의 의미를 익혀보자.
3.1 문제 ) 파일에서 성적을 읽다가 100점을 만나면 그 이후의 성적을 모두 출력하시오(100포함O)
public class breakAndcontinue {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("res/exam.list");
Scanner fscan = new Scanner(fis);
for(boolean found = false; fscan.hasNext();)
{
String word = fscan.next();
int kor = Integer.parseInt(word);
if(kor >= 100)
found = true; // 출력으로 바뀌는 상태변화가 일어난다.
if(!found)
continue; // 상태 변화가 일어나지 않으면 (found=false) 출력하지 않는다.
System.out.printf("%d,", kor);
}
fscan.close();
fis.close();
}
}
3.2 문제 ) 파일에서 성적을 읽다가 100점을 만나면 그 이후의 성적을 모두 출력하시오(100포함x)
public class breakAndcontinue {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("res/exam.list");
Scanner fscan = new Scanner(fis);
for(boolean found = false; fscan.hasNext();)
{
String word = fscan.next();
int kor = Integer.parseInt(word);
if(kor == 100)
found = true;
if(!found || kor == 100)
continue;
System.out.printf("%d," , kor);
}
fscan.close();
fis.close();
}
}
3.3 문제) 파일에서 성적을 읽다가 '두 번째 100 이후의 성적'을 모두 출력하시오(100점 미포함)
public class breakAndcontinue {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("res/exam.list");
Scanner fscan = new Scanner(fis);
for(int count=0; fscan.hasNext();) { // 카운트 변수를 선언해서 상태변화를 표시했다.
String word = fscan.next();
int kor = Integer.parseInt(word);
if(kor==100)
count++;
if(count < 2 || kor ==100)
continue;
System.out.printf("%d,", kor);
}
fscan.close();
fis.close();
}
}
3.4 문제) 파일에서 성적을 5번'부터' 8번 '까지'만 읽어서 다음처럼 화면에 출력하시오.
public class breakAndcontinue {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("res/exam.list");
Scanner fscan = new Scanner(fis);
for(int i=0; fscan.hasNext(); i++) {
String word = fscan.next();
int kor = Integer.parseInt(word);
if (i<4)
continue;
if(i==8)
break;
System.out.printf("%d," ,kor);
}
fscan.close();
fis.close();
}
}
위의 코드들을 통해 우리는 상태변화 변수 found, count의 쓰임을 살펴봤다. 조건문에서 무언가 상태가 바뀌면 상태변화를 생각하자.
3.For문 코드블럭 안에는 변수를 왜 선언하지 않을까?
: 값이 바뀌지 않는다.
found의 값이 계속 false다. found의 true/false값을 이용해 코드를 진행하려는데 만약 for문안에 변수를 쓰면 값을 변화시킬 수 없다.
4.반복문 / 제어문 생각할 점
1.조건을 지정한다. 어떻게 조건을 지정해야할까?
2.인덱스를 쓸거냐 안쓸거냐에 따라 while문을 쓸지 for문을 쓸지 결정한다. 그리고 인덱스의 범위에 주의한다.
3.상태유지를 할거냐 안할거냐(저장변수필요)를 결정한다.
4.제어의 흐름을 어떻게 제어 할 것인가?
5.변수의 가시영역과 생명주기
코드블럭 내에 선언은 한번만 한다. 단 변수는 여러번 대입할 수 있다.
변수는 블럭 들어가기 전에 미리 준비된다(정적 성질)
*정적(static)vs동적(dynamic) 의미
정적: 미리 정해져있다.
동적:그때 상황에 맞게 정해진다.
'뉴렉처 > 자바' 카테고리의 다른 글
[뉴렉처/자바] ★배열 2023.06.21 (0) | 2023.06.21 |
---|---|
[뉴렉처/자바] ★반복문과 제어문 2023.06.20 (0) | 2023.06.20 |
[뉴렉처/자바]★반복문과 제어문 2023.06.19 (1) | 2023.06.19 |
[뉴렉처/자바] ★반복문과 제어문 2023.06.16 (0) | 2023.06.16 |
[뉴렉처/자바] ★반복문과 제어문 2023.06.14 (0) | 2023.06.14 |