【发布时间】:2015-07-30 14:56:59
【问题描述】:
我想知道如何对用户输入进行类型检查。这里我有一个简单的测试来检查用户输入是否在 1 到 10 之间。我想设置它以便用户也可以输入字母,主要是我可以使用输入 'q' 来退出程序。
扫描仪有可以打字检查的部分吗?我的想法是有一个if语句:如果用户输入type int continue,如果不是type int,检查是否是q退出程序,否则输出这是一个错误。以下是我到目前为止的内容,由于类型不匹配,因此在输入数字时会抛出一个表达式。
public static void main(String[] args) {
//Create new scanner named Input
Scanner Input = new Scanner(System.in);
//Initialize Number as 0 to reset while loop
int Number = 0;
do
{
//Ask user to input a number between 1 and 10
System.out.println("At anytime please press 'q' to quit the program.");
System.out.println();
System.out.print("Please enter a number between 1 and 10:");
Number = Input.nextInt();
if (Number == 'Q'|| Number == 'q')
{
System.out.println("You are now exiting the program");
}
else if (Number >= 1 && Number <= 10)
{
System.out.println("Your number is between 1 and 10");
}
else
{
System.out.println("Error: The number you have entered is not between"
+ " 1 and 10, try again");
}
}
//Continue the loop while Number is not equal to Q
while (Number != 'Q' & Number != 'q');
}
}
感谢大家的回复。我有点新,所以 try 语句对我来说是新的,但看起来它会起作用(似乎有点自我解释它的作用)。我会更多地研究它的使用并正确地实现它。
【问题讨论】:
标签: java