首页 > 解决方案 > 如何使用字符串变量

问题描述

我一直在试图弄清楚如何分析输入的变量是数字还是短语,然后输出适当的响应。

System.out.println("Enter the number of lines in your triangle and pyramid");
lines = input.nextInt();
if (lines != int)

有任何想法吗?

标签: java

解决方案


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
}

推荐阅读