[자바JAVA]1066 : [기초-조건/선택실행구조] 정수 3개 입력받아 짝/홀 출력하기(설명), Scanner 기본구분자, whitespace(화이트스페이스)뜻

문제 1066 : [기초-조건/선택실행구조] 정수 3개 입력받아 짝/홀 출력하기(설명)

세 정수 a, b, c가 입력되었을 때, 짝(even)/홀(odd)을 출력해보자.

  • 입력예시
    세 정수 a, b, c 가 공백을 두고 입력된다.
    1
    0 <= a, b, c <= +2147483647
1
1 2 8
  • 출력예시
1
2
3
odd
even
even




코드1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] nums = sc.nextLine().split(" ");
sc.close();

for(int i=0; i<nums.length; i++){
if(Integer.parseInt(nums[i])%2 == 0){
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
}

내가 제일 처음 생각한 코드이다.
최대한 반복을 줄이고싶어서 String 배열로 받아서 if문안에서 int로 변형했다.
좋은 코드가 있을까싶어 다른 코드들도 구글링했는데 더 좋은 코드를 찾았다.




코드2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[3];

for(int i=0; i<3; i++) {
arr[i]= sc.nextInt();
if(arr[i]%2 ==0) {
System.out.println("even");
}
else {
System.out.println("odd");
}
}
sc.close();
}
}




배운 지식

두 코드의 메모리사용과 시간, 코드길이를 비교해보았다

코드1(String Array사용) 코드2(int Array사용)
메모리 14908 14948
시간 112 113
코드길이 590 B 458 B

공백으로 나누어야하니까 String Array만 써야하는 줄 알았는데 int Array도 가능했다.
코드길이도 더 짧다.
어떻게 nextInt()는 space를 받아들일까?




Scanner default delimiter (스캐너 클래스 기본 구분자)

엄청 열심히 검색해서 그 답을 알아냈다.
그 답은 nextInt()메서드가 아닌 Scanner 클래스에 있었다.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
출처 : https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

여기서 말하는 기본 구분자(default delimiter)는 화이트스페이스(whitespace)라고한다.




whitespace (화이트 스페이스)

그렇다면 화이트스페이스(whitespace)가 무엇일까?
화이트 스페이스란 말그대로 의미없는 공백, 탭, 행 등등을 의미한다.
예를 들어 소스코드 끝에 있는 공백이라든지 의미없는 새로운 행이 있다.

  • 화이트 스페이스의 종류
    • space
    • tabs
    • new lines

The Scanner class provides a versatile way of reading data of various types including Files, InputStreams and simple String objects. The input data must be delimited by some character. By default the delimiters are white space (space, tabs, and new lines). The class provides methods for changing the delimiter.
출처 : http://csc.columbusstate.edu/woolbright/java/scanner.html

자바에서는 whitespace인지 아닌지 구분하는 isWhitespace()메서드가 있다.




다른 문제 풀이가 보고싶다면?

Comments