2016-11-18 1 views
-4

사용자가 입력 한 문자열의 길이를 계산하는 프로그램을 만들었습니다. 내 프로그램은 대부분 잘 작동하지만 "Hello World"를 인쇄하면 길이가 5가됩니다 (반면에 11이어야 함). 이 문제를 어떻게 해결할 수 있습니까?문자열 입력의 길이를 계산하십시오.

import java.util.Scanner; 
public class StringLength { 
     public static void main(String[] args){ 
      Scanner in = new Scanner(System.in); 
      System.out.print("Enter the string: \n"); 
      String word = in.next(); 

      System.out.println("The length is: " +word.length()); 

    } 

} 

답변

0
import java.util.Scanner; 
public class StringLength { 
     public static void main(String[] args){ 
      Scanner in = new Scanner(System.in); 
      System.out.print("Enter the string: \n"); 
      String word = in.nextLine(); <----// change it to this 

      System.out.println("The length is: " +word.length()); 

    } 

} 
+3

아마도 이전 질문과 중복되므로 회신해서는 안됩니다. –

0

는 사용 String word = in.nextLine() 대신 String word = in.next()

0

in.next()은 첫 번째 토큰을 읽습니다. 귀하의 경우에는 "안녕하세요".

문자열 전체를 읽으려면 in.nextLine()을 사용해야합니다.

관련 문제