티스토리 뷰

반응형

 

오늘은 Day 1 문제를 풀어보고

코드를 리뷰해보자.

 

Day 1 결과

 


 

영어 문제이긴 하지만

예제와 함께 보면 이해하는 데에 어려움은 없을 것이다.

 

기존에 제시된 i, d, s에 추가로

int형, double형, string형 값을 입력받아

 

출력 조건에 맞게 출력시키면 되는 문제였다.

 

문제는 어렵지 않았으나

많이 낚이는(?) 부분이 있었을 텐데

코드를 통해 설명하겠다.

바로 코드로 들어가보자!

 


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
	
    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";
		
        Scanner scan = new Scanner(System.in);
        int i2 = scan.nextInt();
        double d2 = scan.nextDouble();
        String s2 = scan.nextLine();
        
        System.out.println(i+i2);
        System.out.println(d+d2);
        System.out.println(s+s2);
        scan.close();
    }
}

 

다음과 같이 많이 작성하였을텐데

이렇게 작성하면 틀렸다고 할 것이다.

 

s2를 입력받지 못해서인데

실제로 System.out.println(s2);를 찍어봐도

공백이 출력될 것이다.

 

 

🤔 그럼 어떻게 해야할까?

 

다음의 코드를 보자.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
	
    public static void main(String[] args) {
        int i = 4;
        double d = 4.0;
        String s = "HackerRank ";
		
        Scanner scan = new Scanner(System.in);
        int i2 = scan.nextInt();
        double d2 = scan.nextDouble();
        scan.nextLine();
        String s2 = scan.nextLine();
        
        System.out.println(i+i2);
        System.out.println(d+d2);
        System.out.println(s+s2);
        scan.close();
    }
}

 

다음과 같이 d2를 입력받은 후

scan.nextLine();을 추가하고

s2를 입력받으면 된다.

 

 

🤔 그 이유에 대해 간략하게 살펴보면

nextInt(), nextDouble() 등을 사용한 이후 String을 입력받기 위해 nextLine()을 사용하면

버퍼에 남아있는 \n(Enter값)을 읽어들이기 때문에 nextLine() 메서드가 바로 리턴한다.

 

그래서 nextLine()을 호출하기 전에 nextLine()을 한번 써주면

버퍼에 있는 \n을 읽어 그 다음 문자열이 잘 읽힌다.

 

 

다음의 코드를 작성 후 실행해보면 확실히 이해가 될 것이다.

import java.util.Scanner;

public class Asdf {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        double d = sc.nextDouble();
        String s = sc.nextLine();

        System.out.println("d : " + d);
        System.out.println("s : " + s);
    }
}

 

출력결과

출력결과

 

2.9의 double형만 한 번 입력했을 뿐인데

string은 입력받지 않고 자동으로 출력문을 실행한다.

 

심지어 출력문의 s도 아무값이 없다.

 

 

아까 말한 sc.nextLine();을 추가해보자.

import java.util.Scanner;

public class Asdf {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        double d = sc.nextDouble();
        sc.nextLine();
        String s = sc.nextLine();

        System.out.println("d : " + d);
        System.out.println("s : " + s);

    }
}

 

출력결과

출력결과

 

다음과 같이 잘 나오는 것을 확인할 수 있다.

 

 


오늘은 Day 2 챌린지를 진행해보았다.

엄청 어려운 수준은 아닌데

sc.nextLine()에서 조금 막혔다,,

그래도 새로운 것을 알아서 뿌듯하다 ❗❗

 

그럼 오늘도 열공하자 😊

반응형