您的位置:首页 > 编程语言 > Java开发

本科生java考试练习题目

2014-01-08 13:58 253 查看

前言

论文休息时间,帮实验室的师弟师妹做几道java考试题目,预祝师弟师妹考试取得优异成绩

题目

1、创建3个线程,每个线程睡眠一段时间(0-6秒),然后结束

class SleepFun implements Runnable {
private int sleepTime = 0;

public SleepFun(int time) {
this.sleepTime = time * 1000;
}

@Override
public void run() {
try {
Thread.sleep(this.sleepTime);
System.out.println("Hello World!" + this.sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class TestThread {
public static void main(String args[]) {
SleepFun f1 = new SleepFun(1);
SleepFun f2 = new SleepFun(3);
SleepFun f3 = new SleepFun(5);

Thread t1 = new Thread(f1);
t1.start();

Thread t2 = new Thread(f2);
t2.start();

Thread t3 = new Thread(f3);
t3.start();
}
}


2、编写一个程序,从键盘读入一个实数,然后检查实数是否小于零,是就抛出异常,否则将这个数开平方

import java.util.Scanner;

public class TestException {
public double sqrtNumber(double num) throws Exception {
if (num >= 0) {
return Math.sqrt(num);
} else {
throw new Exception("This number is less than zero!");
}
}

public static void main(String[] args) {
double num;
Scanner cin = new Scanner(System.in);

while (cin.hasNext()) {
num = cin.nextDouble();

try {
TestException te = new TestException();
double res = te.sqrtNumber(num);
System.out.println(res);
} catch (Exception e) {
e.printStackTrace();
}
}

cin.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: