nextInt()、next()和nextLine()的用法
nextInt(): it only reads the int value, nextInt() places the cursor(光标) in the same line after reading the input.(个人理解:nextInt()读取的是Int类型的数据,而对于提交所剩下"\n"还没有读取,因此如果用nextInt()读取后,再用nextLine()读取,读取到的是换行符)
next(): read the input only till the space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input.(个人理解:next() 从第一个有效字符(非空格,非换行符)开始扫描,当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描,获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串)
nextLine(): reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.nextLine(),(个人理解:nextLine()扫描一行内容并作为一个字符串而被获取到。如果需要读取带空格的一串字符串需要使用nextLine(),)
从这其中我们可以知道,使用next()读取后,其实还有一个回车未读取出来,若此时后面跟上一个nextLine()读取的是该回车。碰到nextLine()若Scanner中确实没有东西可以读取,会等待你输入。
而如果想消除这个空格,只需要在next()方法读取完后,在他的后面加一个a.nextLine()释放这个空格,如下图所示。
hasNextInt()的作用
hasNextInt()函数大体意思表示scanner当前的标记的输入是否为int,并不会自动的移动标记。
例如实现一个判断当前到输入是否为数字,不是的话提示输入数字。若是以下代码:当输入的不是数字时,会一直输出请输入数字。