和print()、println()有关的疑惑

ttlibra 2007-03-16 11:27:23
下面有两段程序,其中只有一个地方不同

第一段程序:
*****************
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 :"呢?
...全文
226 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ttlibra 2007-03-17
  • 打赏
  • 举报
回复
这样噢!
谢谢两位的帮助!
craig_wolfdon 2007-03-17
  • 打赏
  • 举报
回复
相当于你多输入了一行,这一行就是回车,所以在扫描器nextLine()的时候就扫描到了
   say some words
For_suzhen 2007-03-17
  • 打赏
  • 举报
回复
public String nextLine()此扫描器执行当前行,并返回跳过的输入信息。 此方法返回当前行的其余部分,不包括结尾处的行分隔符。当前位置移至下一行的行首。
因为此方法会继续在输入信息中查找行分隔符,所以如果没有行分隔符,它可能会缓冲所有输入信息,并查找要跳过的行。


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

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧