栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

扫描仪输入为何不起作用?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

扫描仪输入为何不起作用?

这样说:

int age = input.nextInt();input.nextLine();System.out.println("Great! We're almost done. What are three interests you have?");String interests = input.nextLine();

其余代码可能与您上面的代码相同。

编辑:
它必须是这样的(我的意思是,不将行存储在您的任何变量中),因为

nextInt()
函数不会读取整行,而只是读取下一个整数。因此,当
nextInt()
函数读取时
int
,的“光标”
Scanner
将位于之后的位置
int


例如,如果您在尝试读取时输入多个单词(用空格隔开)

int
,则在您的兴趣变量中,您将
nextInt()
读取之前无法读取的其余行。因此,如果您有:

System.out.println("Okay, " + name + ", you are a " + gender + ". Now, tell me, what is your age?");//Here you enter --> 18 This is a proveint age = input.nextInt();System.out.println("Great! We're almost done. What are three interests you have?");//Here you won't be able to put anythingString interests = input.nextLine();

现在您将存储:

age = 18;interests = "This is a prove";

但是,如果您将代码如下所示:

System.out.println("Okay, " + name + ", you are a " + gender + ". Now, tell me, what is your age?");//Here you enter --> 18 This is a proveint age = input.nextInt();input.nextLine();//Now the Scanner go to a new line (because of the nextLine) but without storing the valueSystem.out.println("Great! We're almost done. What are three interests you have?");//Now you are in a new line and you are going to be able to write. For example --> I am reading this.String interests = input.nextLine();

您现在要拥有的值是:

age = 18;interests = "I am reading this.";

因此,总而言之,如果您有一个

nextInt()
并且试图读取一个
int
,则可以读取它,但是光标将停留在该行的最后,您将无法读取下一行。为此,您必须阅读完整的行而不将其存储在中
input.nextLine();

希望对您有帮助!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/463894.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号