JAVA
while문 쓰는 팁 (백준 11021 자바)
클로키
2020. 5. 14. 15:14
지금까지 while문 반복조건 안에서 변수를 증감할 생각은 못했었는데, 다른 사람들 코드를 보다가 while문 안에서 ++를 시키는 것을 발견했다. 전에 for문과 while문의 차이에 대해 while은 for와 비교해 여러 줄로 작성되는 것을 차이점으로 언급했었는데, 이렇게 괄호 안에서 증감시키면 더 쓰기 간편해진다.
아래 예제에서 while(num > 0) { num--; } 대신 while(num-- > 0) { }으로 쓸 수 있다. 이게 뭐 대단한거라고 좋아하냐^^
< 백준 11021번 A+B - 7 >
입력 : 첫째 줄에 라인 개수, 둘째 줄부터 공백으로 구분된 A와 B
출력 : 형식에 맞게 A+B를 출력
import java.io.*;
class Main{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int num = Integer.parseInt(br.readLine());
int count = 1;
while(num-- > 0){
String line = br.readLine();
int pos = line.indexOf(" ");
int a = Integer.parseInt(line.substring(0,pos));
int b = Integer.parseInt(line.substring(pos+1));
String result = "Case #" + count++ + ": " + Integer.toString(a+b);
bw.write(result);
bw.newLine();
}
bw.flush();
}
}