日期:2014-05-20  浏览次数:20712 次

和print()、println()有关的疑惑
下面有两段程序,其中只有一个地方不同

第一段程序:
*****************
import   java.util.Scanner;

public   class   Practice2_3_1
{
      public   static   void   main(   String   args[]   )
      {
            String   str;
            Scanner   input   =   new   Scanner(System.in);
           
            System.out.print(   "Say   some   words   : "   );
            //注意这句,用的是print,此乃唯一不同之处

            str   =   input.nextLine();
            System.out.printf(   "You   said:\n%s ",   str);
            System.out.println();
      }
}

其执行结果为:
--------------------Configuration:   <Default> --------------------
Say   some   words   :hello   how   are   you
You   said:
hello   how   are   you

Process   completed.
这个结果是预期的

第二段程序
*****************
import   java.util.Scanner;

public   class   Practice2_3_1
{
      public   static   void   main(   String   args[]   )
      {
            String   str;
            Scanner   input   =   new   Scanner(System.in);
           
            System.out.println(   "Say   some   words   : "   );
            //注意这句,用的是println,此乃唯一不同之处
           
            str   =   input.nextLine();
            System.out.printf(   "You   said:\n%s ",   str);
            System.out.println();
      }
}

其执行结果为:
--------------------Configuration:   <Default> --------------------
Say   some   words   :
hello   how   are   you
You   said:
Say   some   words   :

Process   completed.

我的输入都是 "hello   how   are   you "
将两者的输出结果比较:
-1-
Say   some   words   :hello   how   are   you
You   said:
hello   how   are   you
-2-
Say   some   words   :
hello   how   are   you
You   said:
Say   some   words   :

区别就在, "Say   some   words   : "这个提示之后有没有回车.第二段程序执行后为什么我得不到我输入的那句话,得到的却是 "Say   some   words   : "呢?

------解决方案--------------------
public String nextLine()此扫描器执行当前行,并返回跳过的输入信息。 此方法返回当前行的其余部分,不包括结尾处的行分隔符。当前位置移至下一行的行首。
因为此方法会继续在输入信息中查找行分隔符,所以如果没有行分隔符,它可能会缓冲所有输入信息,并查找要跳过的行。


返回:
跳过的行
========================================================
println后面加了个行分隔符,nextLine()可能就把你的Say some words :这一行当成了输入了