Java语言程序设计
2021/10/20 11:10:29
本文主要是介绍Java语言程序设计,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
第十二章练习题
- 12.3 ArrayIndexOutOfBoundsException异常
- InputMismatchException异常
12.3 ArrayIndexOutOfBoundsException异常
- 创建一个由100个随机选取的整数构成的数组。
- 提升用户输入数组的下标,然后显示对应的元素值。如果指定的下标越界,则显示消息“Out of Bounds”。
package Chap12; import java.util.Scanner; public class Three { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] arr = new int[100]; for (int i = 0;i < 100;i++){ arr[i] = (int)(Math.random()*1000); } System.out.print("查询下标:"); try { int num = input.nextInt(); System.out.printf("aar[%d]"+" = "+arr[num],num); } catch (ArrayIndexOutOfBoundsException ex){ System.out.println("Out of Bounds"); } } }
运行结果:
InputMismatchException异常
编写程序,提示用户读取两个整数,然后显示他们的和。程序应该在输入不正确时提示用户再次读取数值。
package Chap12; import java.util.InputMismatchException; import java.util.Scanner; public class Two { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入两个整数:"); while (true){ try{ int num1 = input.nextInt(); int num2 = input.nextInt(); int res = num1 + num2; System.out.println(num1+" + "+num2+" = "+res); System.out.print("请输入两个整数:"); } catch (InputMismatchException ex){ System.out.print("请输入整数:"); /**吸收输入剩下的换行符*/ input.nextLine(); } } } }
运行结果:
这篇关于Java语言程序设计的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-04TiDB 资源管控的对撞测试以及最佳实践架构
- 2024-07-03万字长文聊聊Web3的组成架构
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现