我的代码应做到以下这部分:if语句和的try-catch不会阻止错误
- 检查输入是INT型(的try-catch)
- 如果输入一个INT,检查它是否在列表之间:
代码
public static void selection(List<Performer> listperformer)
{
int i=0;
List<Performer> idlist = new ArrayList<Performer>();
Scanner sclocal = new Scanner(System.in);
if(listperformer.isEmpty() == true)
{
System.out.println("- empty -");
return;
}
else
{
System.out.println("Enter IDs:");
int id;
id=sclocal.nextInt();
while(sclocal.hasNext())
{
try{
id=sclocal.nextInt();
}catch(InputMismatchException exception)
{
System.out.println("Invalid input!");
}
if(listperformer.size() <= id || id < 0)
{
System.out.println("Invalid input! 294");
return;
}
else
{
idlist.add(listperformer.get(id));
}
id=sclocal.nextInt();
}
}
不起作用。问题: 1.
- ,如果我把一个错误的ID,他问我把在另一并在此之后 抛出一个异常
- ,如果我把一个字符串抛出一个“InputMismatchException时”
我们假设,我们列表中只有三个条目。 结果:
Input: 5
Output:
Input: 4
Output: Invalid input! 294
Input: asdf
Output: Exception in thread "main" java.util.InputMismatchException...
你观察到的“有问题”的用例的工作原理完全一样,意,或能更好地说 - 因为它是编码和预期。 – Shark
为了更好地理解你的代码在做什么,使用几乎可以肯定内置到IDE(或独立调试器)中的调试器,并逐步浏览代码。使用调试器是学习编程的重要部分,而非可选部分。 –