我一直在尝试弄清楚如何分析输入的变量是数字还是短语,然后输出适当的响应。
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 - 如何使用字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52430066/