2 回答
![?](http://img1.sycdn.imooc.com/545862e700016daa02200220-100-100.jpg)
TA贡献1712条经验 获得超3个赞
这就是我要做的:
public static void playerChoice()
{
try
{
String inStr = input.nextLine();
int inInt = Integer.parseInt(inStr); // throws exception.
if (inInt < 0 || inInt > 6) // If number out of range, try again.
{
System.out.println("Error. You have to choose a number from 0 to 6");
playerChoice();
}
else
{
choice = inInt;
}
}
catch (NumberFormatException ex) // If exception, try again.
{
System.out.println("Invalid input! You have to enter a number");
playerChoice();
}
}
除了依赖之外Scanner.nextInt(),我将首先以String的形式读取输入(因为在此步骤中不涉及任何解析),然后将其Integer.parseInt()用于手动解析。通常,将读取/获取与转换/解析分开是一个好习惯。
![?](http://img1.sycdn.imooc.com/54584c9c0001489602200220-100-100.jpg)
TA贡献1796条经验 获得超4个赞
经过一番谷歌搜索之后,看起来好像在抛出异常后并没有清除输入(请参阅input.nextInt()如何工作?)。
结果,由于您没有调用“ input.next();”,因此它将继续读取相同的输入,意识到它不是整数并抛出异常。
解决方案:
try {
choice = (int) input.nextInt();
while (choice<0 || choice>6) {
System.out.println("Error. You have to choose a number from 0 to 6");
playerChoice();
} }
catch (InputMismatchException ex) {
System.out.println("Invalid input! You have to enter a number");
input.next();
playerChoice();
}
添加回答
举报