Java next怎么用_Java中Scanner的nextInt(),next(),nextLine()方法总结

今天在java上机课时遇到了个小问题,使用Scanner输入数据时,使用了一次nextInt(),一次nextLine(),却只接收了一个整数。代码如下

code1:

a4c26d1e5885305701be709a3d33442f.png

1package cn.dx;2

3import java.util.Scanner;4

5 public classScannerTest {6

7 public static voidmain(String[] args) {8 Scanner in = new Scanner(System.in);9 System.out.println("请输入一个整数");10 while(in.hasNextInt()){11 int num = in.nextInt();12 System.out.println("请输入一个字符串");13 String str = in.nextLine();14 System.out.println("num="+num+",str="+str);15 System.out.println("请输入一个整数");16}17}18 }

a4c26d1e5885305701be709a3d33442f.png

运行结果为:

请输入一个整数

1231

请输入一个字符串

num=1231,str=

请输入一个整数

第二个String类型的参数没有读取进来。

自己查看了下nextInt()和nextLine()方法的官方文档

nextLine()

Advances this scanner past the current line and returns the

input that was skipped. This method returns the rest of the current

line, excluding any line separator at the end. The position is set

to the beginning of the next line.

nextInt()方法会读取下一个int型标志的token.但是焦点不会移动到下一行,仍然处在这一行上。当使用nextLine()方法时会读取改行剩余的所有的内容,包括换行符,然后把焦点移动到下一行的开头。所以这样就无法接收到下一行输入的String类型的变量。

之后改用了next()方法

code2.

a4c26d1e5885305701be709a3d33442f.png

1 packagecn.dx;2

3 importjava.util.Scanner;4

5 public classScannerTest {6

7 public static voidmain(String[] args) {8 Scanner in = newScanner(System.in);9 System.out.println("请输入一个整数");10 while(in.hasNextInt()){11 int num =in.nextInt();12 System.out.println("请输入一个字符串");13 String str =in.next();14 System.out.println("num="+num+",str="+str);15 System.out.println("请输入一个整数");16}17}18 }

a4c26d1e5885305701be709a3d33442f.png

运行后结果是正确的,运行结果如下。

请输入一个整数

123

请输入一个字符串

sdjakl

num=123,str=sdjakl

请输入一个整数

213 jdskals

请输入一个字符串

num=213,str=jdskals

请输入一个整数

试验后发现next()方法是以换行或者空格符为分界线接收下一个String类型变量。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值