java - 在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"));
解决方案
你可以这样做:
try {
...
} catch (ArrayIndexOutOfBounds ex) {
...
}
推荐阅读
- algorithm - “Exact Cover”维基百科详细示例,关于最后一步的问题
- ruby-on-rails - 意外标记:使用 Uglifier 时 ES6 类上的运算符 (=)
- css - 如何一键多次更改按钮的背景颜色?
- c# - 从控制器下载 zip 文件不显示下载或任何错误
- php - 如何使用 PHP 打印 CSV 文件的行?
- css - CSS 未应用于单独的 ejs 文件
- javascript - 我重构的香草 JS 按钮单击不起作用
- ios - 在 SwiftUI 中创建表格的适当方法
- ignite - 在 ApacheIgnite 中无法从 sqlline.bat 访问表
- flutter - 使用flutter上的animated_text_kit插件顺序启动多个文本的显示