首页 > 解决方案 > 在java中使用try和catch查找元素数组

问题描述

所以,我有两个数组,第一个是人名,第二个是年龄。然后,我在输出中创建了一个 id,这样我就可以找到要打印的 id。

例如 :

ID 姓名 年龄

1 卢卡斯 15

2 漏洞 16

但是,我想使用 try 和 catch 来防止用户在数组之外找到一个 id。

import java.util.Scanner;

Scanner input = new Scanner(System.in);
String[] name = {"Lucas","Vulnere"};
int[] age = {15, 16};
String answer = "";
System.out.println("ID\tNames\tAges");
for(i=0; i < age.length; i++)
{
System.out.println((i+1) +"\t"+name[i]+"\t"+age[i]);
}

do {
try {

System.out.println("Find people by id");
int id = input.nextInt();
}

catch(//WhatExceptionShouldIUse){
System.out.println("Id not found");
}

System.out.println("Result : ");
System.out.println("id : "+id);
System.out.println("Name : "+name[id-1]);
System.out.println("Age : "+age[id-1]);

System.out.println("Want to try to find it again? Y/N");
answer = input.next();
}while(answer.equalsIgnoreCase("Y"));

标签: javaarraysexception

解决方案


你可以这样做:

try {
    ...
} catch (ArrayIndexOutOfBounds ex) {
    ...
}

推荐阅读