2016-11-18 140 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()来读取整个字符串。