Q.1.
Advanced Java:
A)
Write a socket program in Java to check whether given number is prime or not.
Display
result on client terminal.
Answer :
//Client
import java.io.*;
import java.net.*;
public class Slip3A {
public static void main(String args[]) throws Exception {
Socket s = new Socket("localhost", 7500);
DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter any number:");
String n = din.readLine();
System.out.println("====================");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeBytes(n + "\n");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readLine());
}
}
//Server
import java.io.*;
import java.net.*;
public class Slip3A1 {
public static void main(String args[]) throws Exception {
ServerSocket ss = new ServerSocket(7500);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
int n = Integer.parseInt(dis.readLine());
int i, cnt = 0;
for (i = 2; i < n; i++) {
if (n % i == 0)
cnt++;
break;
}
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
if (cnt == 0)
dos.writeBytes(n + " is prime
number.");
else
dos.writeBytes(n + " is not prime
number.");
s.close();
}
}
B)
Write a java program using applet for bouncing ball, for each bounce color of
ball
should
change randomly.
Answer :
import java.awt.*;
import java.awt.event.*;
public class Slip3B extends Frame implements Runnable {
private int x, y, w, h, f;
private Color c = Color.red;
public Slip3B() {
setTitle("Bouncing Boll");
setSize(400, 400);
setVisible(true);
w = getWidth();
h = getHeight();
x = (int) (Math.random() * getWidth());
y = (int) (Math.random() * getHeight());
Thread t = new Thread(this);
t.start();
}
public void run() {
while (true) {
switch (f) {
case 0:
y++;
if (y > h - 50) {
c = new Color((int) (Math.random() * 256), (int) (Math.random() * 256),
(int) (Math.random() * 256));
f = 1;
}
break;
case 1:
y--;
if (y < 0) {
c = new Color((int) (Math.random() * 256), (int) (Math.random() * 256),
(int) (Math.random() * 256));
f = 0;
}
}
repaint();
try {
Thread.sleep(10);
} catch (Exception e) {
}
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(c);
g.fillOval(x, y, 20, 20);
}
public static void main(String args[]) {
new Slip3B();
}
}
No comments:
Post a Comment