版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014067137/article/details/82177894
package test0829;
/**
* @author wyl
* @time 2018年8月29日上午9:10:43
* 随机产生10个整数(1-100),求生成整数的最大值和最小值
*/
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr=new int[10];
for(int i=0;i<10;i++){
arr[i]=(int) (Math.random()*100)+1;
System.out.print(arr[i]+" ");
}
System.out.println();
int max=arr[0];
int min=arr[0];
for(int i=0;i<10;i++){
if (arr[i]>max) {
max=arr[i];
}
if (arr[i]<min) {
min=arr[i];
}
}
System.out.println("MAX:"+max);
System.out.println("MIN:"+min);
}
}
编写一个异常类MyException,再编写一个类Student,
该类有一个产生异常的方法public void speak(int m) throws MyException,
要求参数m的值大于1000时,方法抛出一个MyException对象。
最后编写主类,在主类的main 方法中使用Student 创建一个对象,
让该对象调用speak方法(m 参数设为1500)
package test0829;
/**
* @author wyl
* @time 2018年8月29日上午9:23:08
*/
public class MyException extends Exception {
String mes;
public MyException(int m) {
// TODO Auto-generated constructor stub
mes="数字不能大于1000";
}
@Override
public String toString() {
// TODO Auto-generated method stub
return mes;
}
}
package test0829;
/**
* @author wyl
* @time 2018年8月29日上午9:22:01
*/
public class Student {
public void speak(int m) throws MyException{
if (m>1000) {
MyException exception=new MyException(m);
throw exception;
}
System.out.println("i can speak "+m+"words in 3 minutes.");
}
}
package test0829;
/**
* @author wyl
* @time 2018年8月29日上午9:25:52
*/
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student student=new Student();
try {
student.speak(100);
student.speak(12345);
} catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}