java scanner类成员_【Java】 Scanner类的几个方法

本文详细介绍了Java中Scanner类的nextInt(), next()和nextLine()方法的使用及其潜在问题。nextInt()读取整数但保留换行符,next()读取单词,而nextLine()读取整行。当nextInt()或类似方法后直接使用nextLine()时,会遇到输入问题。解决办法是在nextInt()后添加nextLine()来消耗遗留的换行符。
摘要由CSDN通过智能技术生成

通过 Scanner 类可以获取用户的输入,创建 Scanner 对象的基本语法如下:

Scanner sc = new Scanner(System.in);

nextInt()、next()和nextLine()

nextInt(): it only reads the int value, nextInt() places the cursor(光标) in the same line after reading the input.(nextInt()只读取数值,剩下”\n”还没有读取,并将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.(next()只读空格之前的数据,并且cursor指向本行)

next() 方法遇见第一个有效字符(非空格,非换行符)时,开始扫描,当遇见第一个分隔符或结束符(空格或换行符)时,结束扫描,获取扫描到的内容,即获得第一个扫描到的不含空格、换行符的单个字符串。

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.

nextLine()时,则可以扫描到一行内容并作为一个字符串而被获取到。

public class NextTest{

public static void main(String[] args) {

String s1,s2;

Scanner sc=new Scanner(System.in);

System.out.print("请输入第一个字符串:");

s1=sc.nextLine();

System.out.print("请输入第二个字符串:");

s2=sc.next();

System.out.println("输入的字符串是:"+s1+" "+s2);

}

}

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

请输入第一个字符串:abc

请输入第二个字符串:def

输入的字符串是:abc def

View Code

//s1、s2交换

public class NextTest {

public static void main(String[] args) {

String s1,s2;

Scanner sc=new Scanner(System.in);

System.out.print("请输入第一个字符串:");

s1=sc.next();

System.out.print("请输入第二个字符串:");

s2=sc.nextLine();

System.out.println("输入的字符串是:"+s1+" "+s2);

}

}

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

请输入第一个字符串:abc

请输入第二个字符串:输入的字符串是:abc

View Code

nextLine()自动读取了被next()去掉的Enter作为他的结束符,所以没办法给s2从键盘输入值。

如double nextDouble() , float nextFloat() , int nextInt() 等与nextLine()连用时都存在这个问题,解决的办法是:在每一个 next()、nextDouble() 、 nextFloat()、nextInt() 等语句之后加一个nextLine()语句,将被next()去掉的Enter结束符过滤掉。

public class NextTest{

public static void main(String[] args) {

String s1,s2;

Scanner sc=new Scanner(System.in);

System.out.print("请输入第一个字符串:");

s1=sc.next();

sc.nextLine();

System.out.print("请输入第二个字符串:");

s2=sc.nextLine();

System.out.println("输入的字符串是:"+s1+" "+s2);

}

}

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

请输入第一个字符串:abc

请输入第二个字符串:def

输入的字符串是:abc def

View Code

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值