Question - 1 Write a java program to implement the following functions: Evaluate
ID: 3540630 • Letter: Q
Question
Question - 1
Write a java program to implement the following functions:
Evaluate a integer, if the value is in the range 20-2000, then the programs print out the value; if the value is out of the range 20-2000, then it throws an exception, and display a message " the value is out of the range 20-2000". You must use try and catch blocks to implement it in your programs.
Tips: in order to simplify the code, you can hard code the value in your code, for instance, define a method setX( int value) at some place of your code, if calling setX(1500), it will generate an exception, and if calling setX(100), it will generate a correct result.
When you run your code, the output results likes: If you set the value 100, just print out the correct result 100. If the value is 1500, the Exception will show up.
Question 2
Write the programs to implement the following functions:
The thread with higher priority calculates the sum of the integers from 1 to 10; and the thread with lower priority calculates the sum of the integers from 11 to 20. You must use Java threads to implement it in your programs.
Explanation / Answer
// PROGRAM 1
public class test
{
public static void setX(int y) throws Exception
{
if(y<20 || y>2000)
throw new Exception("the value is out of the range 20-2000");
System.out.println("Value of x is " + y);
}
public static void main(String[] args)
{
try
{
setX(100);
}
catch(Exception e)
{
System.out.println("Exception thrown :" + e);
}
try
{
setX(2500);
}
catch(Exception e)
{
System.out.println("Exception thrown :" + e);
}
}
}
//PROGRAM 2
class MyThread extends Thread
{
private int x;
public MyThread(int k)
{
x=k;
}
public void run ()
{
int sum =0;
for (int i=1+x; i<=10+x; i++)
{
sum = sum + i;
System.out.println("Thread #"+(x%9)+ " sum is " + sum);
}
}
}
public class sum_using_threads
{
public static void main (String [] args)
{
MyThread mt = new MyThread(0);
mt.setPriority(Thread.MAX_PRIORITY);
mt.start ();
MyThread mt1 = new MyThread(10);
mt1.setPriority(Thread.MIN_PRIORITY);
mt1.start();
}
}
/* SAMPLE OUTPUT
Thread #0 sum is 1
Thread #0 sum is 3
Thread #1 sum is 11
Thread #1 sum is 23
Thread #1 sum is 36
Thread #0 sum is 6
Thread #0 sum is 10
Thread #1 sum is 50
Thread #0 sum is 15
Thread #0 sum is 21
Thread #0 sum is 28
Thread #1 sum is 65
Thread #0 sum is 36
Thread #0 sum is 45
Thread #1 sum is 81
Thread #0 sum is 55
Thread #1 sum is 98
Thread #1 sum is 116
Thread #1 sum is 135
Thread #1 sum is 155
*/