2016-11-18 138 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()來讀取整個字符串。