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.每次输入时将光标点到下一行。

发布了19 篇原创文章 · 获赞 7 · 访问量 9934

猜你喜欢

转载自blog.csdn.net/weixin_42297075/article/details/86624174
今日推荐