java中next(),nextInt()和nextLine()

来源:互联网 发布:网络性能测试包括什么 编辑:程序博客网 时间:2024/06/04 18:11

一、解释

nextInt(): it only reads the int value, nextInt() places the cursor in the same line after reading the input.
它只能读取int型的输入。并且cursor放在该行中。

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.
它遇到space会停止读取!同样将cursor放在该行中。

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.
它会读取一行中的所有内容!包括\n换行符。并且它会将cursor放到下一行。

二、举例

public class Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        Scanner input=new Scanner(System.in);        System.out.println("输入数字:");        System.out.println("nextInt()获取:"+input.nextInt());        System.out.println("输入数字+字符串组合:");        //System.out.println("nextInt()获取:"+input.nextInt());        System.out.println("next()获取:"+input.next());        System.out.println("输入带有空格的字符串:");        System.out.println("next()获取:"+input.next());        System.out.println("nextLine()获取:"+input.nextLine());    }}

结果:

输入数字:
123
nextInt()获取:123
输入数字+字符串组合:
123ab
next()获取:123ab
输入带有空格的字符串:
i am boy
next()获取:i
nextLine()获取: am boy

解析:可以很清楚的看到他们的用法。当输入带有空格的字符串时,next()获取输入知道遇到第一个空格,并将cursor停在这里。然后nextLine()继续从空格处开始获取本行的输入直到\n(包含\n),并将输入cursor置于下一行。

原创粉丝点击