下面有两段程序,其中只有一个地方不同第一段程序:
*****************
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 youProcess 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 :"呢?
*****************
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 youProcess 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 :"呢?
因为此方法会继续在输入信息中查找行分隔符,所以如果没有行分隔符,它可能会缓冲所有输入信息,并查找要跳过的行。
返回:
跳过的行
========================================================
println后面加了个行分隔符,nextLine()可能就把你的Say some words :这一行当成了输入了
say some words