next()nextLine()以及nextInt()的区别及用法

next()、nextLine()、nextInt()作为scanner内置的方法
他们的区别在于对于空格的处理方式不同,以及返回值不同。
使用nextLine()方法时,不将空格看做是两个字符串的间隔,而是看作字符串的一部分,返回时,它作为String类型一并返回:

public class demo {
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
        System.out.println("使用nextLine()方法,并且输入为:");
        String n=sc.nextLine();
        System.out.println("输出为:");
        System.out.println(n);
	}
}

使用next()方法时,将空格看作是两个字符串的间隔:

public class demo {
	public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        System.out.println("使用next()方法,将空格作为间隔符。输入为:");
        while(sc.hasNext()){
            System.out.print("输出为:");
            String n=sc.next();
            System.out.print(n);
        }
}

使用nextInt()方法时,与next()方法类似,只是它的返回值是int类型的,依旧将空格看作是两个输入的数据的间隔

public class demo {
	public static void main(String args[]){
		Scanner sc=new Scanner(System.in);
		System.out.println("使用nextInt()方法,将空格作为间隔符。输入为:");
		while(sc.hasNext()){
			System.out.print("输出为:");
			int n=sc.nextInt();
		    System.out.print(n);
		}
	}
}

注意:当使用nexInt()方法时,只能输入int类型的数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值