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

一、解释

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置于下一行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值