java scanner相关问题

前段时间做数据结构课设,在控制台中进行一些输入,其中用到了不少scanner的方法,之前没怎么注意,导致出现了好多问题,现简单总结以下:

一、nextInt,nextLine,next三者区别

nextInt():

it only reads the int value, nextInt() places the cursor in
the same line after reading the input.

此方法只读取整型数值,并且在读取输入后把光标留在本行

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.

读取输入直到遇见空格。此方法不能读取被空格分隔开的内容,并且在读取输入后把光标留在本行

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.

读取包括空格在内的输入,而且还会读取行尾的换行字符\n,读取完成后光标被放在下一行

二、常见问题

1.输入数字进行选择功能时,未等继续输入,就自动跳下一行

int i;
Scanner s=new Scanner(System.in);
i=s.nextInt();
System.out.println("input yout name")
String name=s.nextLine();
System.out.println("input yout sex")

比如,我们输入数字1并按回车换行,这时,控制台不会等我们输入name,就直接显示

input your name

input your sex

原因:

nextInt()方法只读取整数,当我们按回车时它并没有读取,这个换行符就被String name=s.nextLine();语句读取了,所以出现直接跳过。

解决办法:

在nextInt后买你再加一条s.nextLine(),来读取换行符。

2.当需要输入多个数据,用空格隔开的时候 ,使用next()会报数组越界错误

原因:

next()读取输入直到遇见空格。此方法不能读取被空格分隔开的内容,并且在读取输入后把光标留在本行

解决办法:

使用其他符号进行分割,或者使用nextLine();

3.中文输入出现如,输入信息楼,打印输入内容测试却为信息信息楼,或者xinxi信息楼等错误。

原因:eclipse中文输入的bug

解决办法:

1.cmd运行

2.每次输入时将光标点到下一行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值