강의

멘토링

커뮤니티

Inflearn Community Q&A

haewoni's profile image
haewoni

asked

Introduction to Java Algorithm Problem Solving: Coding Test Preparation

12. Cipher (replace(), parseInt(string, 2))

runtime error

Written on

·

246

0

안녕하세요 선생님,
채점하면 런타임 에러 나오는데.. 코드 한 번 봐주실 수 있을까요?

import java.util.Scanner;

  

public class Main {

  public static void main(String[] args){

    Scanner in=new Scanner(System.in);

    int n = in.nextInt();

    String str = in.nextLine();

    in.close();

    String result = password(str,n);

    System.out.println(result);

    

    

  }

  

  public static String password(String s, int n){

    String result = "";

    for(int i=0;i<n;i++){

      String sub = s.substring(0,7).replace('#','1').replace('*','0');

      int num = Integer.parseInt(sub,2);

      result += (char)num;

      s = s.substring(7);

    }

    return result;

  }

}

java코테 준비 같이 해요!

Answer 2

2

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

nextInt()는 공백이나 줄바꿈 같은 분리자를 입력버퍼에서 무시하고 읽어드립니다. 하지만 nextLine()은 분리자까지 읽어드리는 메서드입니다.

즉 nextInt가 무시하고 읽지 않은 줄바꿈 분리자를 nextLine()이 줄바꿈만 읽고 끝나버리는 코드입니다.

위 코드를 실행시켜서 문제에 있는 예제 입력을 넣어보세요.

해결하는 방법은 nextLine() 를 한 번 넣어주어 줄바꿈을 읽어 드리고 그 다음 nextLine()을 다시 써서 문장을 읽으면 됩니다. 

public class Main {

  public static void main(String[] args){

    Scanner in=new Scanner(System.in);

    int n = in.nextInt();

    in.nextLine();
    String str = in.nextLine();

    in.close();

    String result = password(str,n);

    System.out.println(result);
  }

0

haewoni님의 프로필 이미지
haewoni
Questioner

감사합니다 선생님~~ㅎㅎ

haewoni's profile image
haewoni

asked

Ask a question