写在前面的话:考试周越来越近,各个科目也纷纷响应了有些棘手的大作业,加上自己为了项目的一点点努力,当然还有准备喜欢的科目,渐渐变得压力缠身,前天下决心早睡早起,坚持了一天昨天就以失眠告终…也时常在思考好好做事的意义,深深感到对未来的无力感,于是晚上偷偷流泪写了一些丧丧的文字释放压力,拼命说服自己不要放弃。
事实证明,404会被解开的,warning会被消除的,坏事情是可以变成好事情的,世界上没有魔法,有魔力的人是你呀。
“只有一件事会使人疲劳,摇摆不定和优柔寡断。而每做一件事,都会使人身心解放,即使把事情办坏了,也比什么都不做强。”
这次是有关自定义异常类和集合容器的题目,不得不说集合容器的输出还是有点意思,受其用法的启发,终于得到了正确结果。
No.12 自定义异常类MyException
题目:键盘输入成绩,自定义异常类MyException用于检测输入的成绩大于100或者小于0时,抛出异常,否则就输出成绩。
import java.util.*;
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class Score {
public void judge(int n) throws MyException{
if(n > 100 || n < 0) {
throw new MyException("error!");
}
else {
System.out.println("Your score is:" + n);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input your score");
int n = in.nextInt();
Score vm = new Score();
try {
vm.judge(n);
} catch (MyException e) {
System.out.println("Error,score should be in 0-100.");
}
}
}
No.13 自定义异常类NegativeException和ZeroException
题目:输入两个数,输出两个数的商,自定义异常类NegativeException和ZeroException用于检测输入的除数为负数和零时,抛出异常。
import java.util.Scanner;
class NegativeException extends Exception {
public NegativeException(String message) {
super(message);
}
}
class ZeroException extends Exception {
public ZeroException(String message) {
super(message);
}
}
public class Number {
public void judge(double n, double m) throws NegativeException, ZeroException {
if(m < 0) {
throw new NegativeException("error!");
}
else if(m == 0) {
throw new ZeroException("error!");
}
else {
System.out.println("Divisor is : " + (double)n / (double)m);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please input first number: ");
double n = in.nextDouble();
System.out.println("Please input second number: ");
double m = in.nextDouble();
Number vm = new Number();
try {
vm.judge(n, m);
} catch (NegativeException e) {
System.out.println("The divisor, " + (int)m + ", could not be negative!");
} catch (ZeroException e) {
System.out.println("The divisor, " + (int)m + ",could not be zero!");
}
System.out.println("finally!");
}
}
No.14 ArrayList集合
题目:输入学生个数和名字,使用ArrayList集合存储学生序号和名字,并显示所有的学生信息。
import java.util.*;
public class Student {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i, j = 0;
String e;
System.out.println("How many students?");
int n = in.nextInt();
if(n > 0) {
System.out.println("Please input the names of students:");
}
ArrayList<String> h = new ArrayList<String>();
for(i = 0; i < n; i++)
{
e = in.next();
h.add(e);
}
System.out.println("All the students bellow:");
Iterator it1 = h.iterator();
while (it1.hasNext()) {
j++;
e = (String) it1.next();
System.out.println(j + ":" + e);
}
}
}