转自博客: http://www.cn blogs.com/skyar/p/5892825.html
说明:
nextint (: itonlyreadstheintvalue,nextint ) placesthecursorinthesamelineafterreadingtheinput。
next (3360 readtheinputonlytillthespace.it can ' treadtwowordsseparatedbyspace.also,next ) placesthecursorinthesamelline
nextline (: readsinputincludingspacebetweenthewords ) thatis,itreadstilltheendofline(n ).Once the input is read,nextlid
看完之后nextInt ()、next () )、nextLine () )的区别很明显,但我认为最容易弄错的是cursor问题。
请看以下代码:
1 import java.util.Scanner; 2 publicclassmaxmap {4publicstaticvoidmain (string [ ] args ) )5scannerCIN=newscanner ) system.in ); 6 int n=cin.nextInt (; 7 String str=cin.nextLine (; 8system.out.println('end ' ); 9 }10 }执行后的结果:
从执行结果来看,String str=cin.nextLine (); 这一行的代码。
实际上并不是这样,因为nextInt ()只读取数值,剩下的'n '还没有读取,所以将cursor纳入了本职工作。 nextLine ()读取“n”并退出(nextLine ) readstilltheendofline(n )。
若要在nextInt () )之后读取行,必须在nextInt () )之后添加cin.nextLine (),如以下代码所示
import java.util.Scanner; publicclassmaxmap { publicstaticvoidmain (string [ ] args ) scannerCIN=newscanner ) system.in; int n=cin.nextInt (; cin.nextLine (; String str=cin.nextLine (; system.out.println('end ' ); }正在查看以下代码:
1 import java.util.Scanner; 2 publicclassmaxmap {4publicstaticvoidmain (string [ ] args )5scannerCIN=newscanner ) system.in ); 6 String n=cin.next (; 7 //cin.nextLine (; 8 String str=cin.nextLine (; 9system.out.println('end ' ); 10system.out.println(next ) (read:' n ) n ); 11system.out.println(nextline ) (read: ) str ); 12 ) 13 )执行结果:
理由: next ) )只读取空格前面的数据,cursor指本职工作,后面的nextLine ) )继续读取前面剩下的数据。
要读取整行,请使用nextLine ()。
也可以使用nextLine ()读取数字,但需要转换。 integer.parseint (CIN.nextline ) )。
注意与next ()、nextInt ()、nextLine ()、nextLine ()一起使用时,next ()、nextInt ()往往会读取部分数据('n '或留在空格之后的数据)。