在java中获取整数输入
我实际上是java编程的新手,发现很难接受整数输入并将其存储在变量中...如果有人能告诉我如何做到这一点或提供一个示例,例如将用户给出的两个数字相加,我会很高兴..
I am actually new to java programming and am finding it difficult to take integer input and storing it in variables...i would like it if someone could tell me how to do it or provide with an example like adding two numbers given by the user..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是我的条目,包含相当强大的错误处理和资源管理:
Here's my entry, complete with fairly robust error handling and resource management:
java.util.Scanner
< /a> 是完成此任务的最佳选择。从文档中:
读取
int
只需两行。不过,请不要低估Scanner
的强大功能。例如,以下代码将不断提示输入数字,直到给出一个数字:这就是您所需要编写的全部内容,并且感谢
hasNextInt()
你不必担心任何Integer.parseInt< /code> 和
NumberFormatException
根本没有。另请参阅
相关问题
其他示例
扫描器
可以使用java.io.File
,或普通字符串
。下面是使用
Scanner
标记String
并一次性解析为数字的示例:这是使用正则表达式的稍微更高级的用法:
如您所见,
扫描仪
相当强大!您应该更喜欢它StringTokenizer
,现在是一个遗留类。另请参阅
相关问题
java.util.Scanner
is the best choice for this task.From the documentation:
Two lines are all that you need to read an
int
. Do not underestimate how powerfulScanner
is, though. For example, the following code will keep prompting for a number until one is given:That's all you have to write, and thanks to
hasNextInt()
you won't have to worry about anyInteger.parseInt
andNumberFormatException
at all.See also
Related questions
Other examples
A
Scanner
can use as its source, among other things, ajava.io.File
, or a plainString
.Here's an example of using
Scanner
to tokenize aString
and parse into numbers all at once:Here's a slightly more advanced use, using regular expressions:
As you can see,
Scanner
is quite powerful! You should prefer it toStringTokenizer
, which is now a legacy class.See also
Related questions
你的意思是来自用户的输入
you mean input from user
如果您正在谈论来自控制台输入的这些参数或任何其他
String
参数,请使用 staticInteger#parseInt()
方法将它们转换为整数
。If you are talking about those parameters from the console input, or any other
String
parameters, use staticInteger#parseInt()
method to transform them toInteger
.