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

版权声明:本文为博主原创文章,未经博主允许不得转载。   https://blog.csdn.net/m0_37695351/article/details/79254221                
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类型的数据。
 

来源:https://blog.csdn.net/m0_37695351/article/details/79254221

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值