java - 如何使用字符串变量
问题描述
我一直在试图弄清楚如何分析输入的变量是数字还是短语,然后输出适当的响应。
System.out.println("Enter the number of lines in your triangle and pyramid");
lines = input.nextInt();
if (lines != int)
有任何想法吗?
解决方案
Scanner
要求您在调用该方法之前检查它看到的输入类型。nextXyz
if (lines != int)
一旦你调用nextInt()
,再检查你有什么样的输入已经太晚了:为了nextInt
成功,当前点必须有一个可用的;int
否则会抛出异常。
使用hasNextInt
方法检查输入缓冲区中当前点的内容:
if (input.hasNextInt()) {
lines = input.nextInt();
} else {
System.out.println("Please enter a number");
input.nextLine(); // Drop the current input up to the end-of-line marker
}
推荐阅读
- java - UCP-在启动池时无法创建 initialPoolSize 连接:java.lang.NullPointerException-
- reactjs - 为什么reducer会抛出ReferenceError?
- typo3 - 如何在前端显示我的站点包的版本?
- mysql - MySQL 8 . “secure_file_priv”错误。无法覆盖以更改从 .CSV 文件加载数据的安全模式
- java - Java 运行时 exec 获取字符串数组的错误
- reactjs - React:编辑和替换用户输入(onChange)
- r - 如何密码保护从数据框中导出的 Excel?
- azure-data-factory - 映射数据流公共数据模型源连接器日期时间/时间戳列无效?
- javascript - 单击复选框时,如何在单个字段上使用 jquery 禁用客户端验证?
- c# - code_verifier 与 PKCE 授权请求中提供的 code_challenge 不匹配