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

猜你喜欢

转载自blog.csdn.net/qq_42058441/article/details/86442268
今日推荐