[go: up one dir, main page]

0% found this document useful (0 votes)
12 views52 pages

Oops Record

Uploaded by

santhikala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views52 pages

Oops Record

Uploaded by

santhikala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

1A.

SEQUENTIAL SEARCH
Program:
class GFG {
public static int search(int arr[], int x)
{
int n = arr.length;
for (int i = 0; i< n; i++) {
if (arr[i] == x)
return i;
}
return -1;
}
public static void main(String args[])
{
intarr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int result = search(arr, x);
if (result == -1)
System.out.print( "Element is not present in array");
else
System.out.print("Element is present" + " at index " + result);
}
}
Output:
1B.BINARY SEARCH
Program:
classBinarySearch {
intbinarySearch(intarr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
returnbinarySearch(arr, l, mid - 1, x);
returnbinarySearch(arr, mid + 1, r, x);
}
return -1;
}
public static void main(String args[])
{
BinarySearchob = new BinarySearch();
intarr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 3;
int result = ob.binarySearch(arr, 0, n - 1, x);
if (result == -1)
System.out.println("Element not present");
else
System.out.println("Element found at index " + result);
}
}
Output:
1C.QUADRATIC SORT ALGORITHM --SELECTION SORT
Program:
// Java program for implementation of Selection Sort
Class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
// One by one move boundary of unsorted subarray
for (inti = 0; i< n-1; i++)
{
// Find the minimum element in unsorted array
Int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] <arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Prints the array
voidprintArray(intarr[])
{
int n = arr.length;
for (inti=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver code to test above
public static void main(String args[])
{
SelectionSortob = new SelectionSort();
intarr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}

Output:
1D.QUADRATIC SORT ALGORITHM--INSERTION SORT
Program:
// Java program for implementation of Insertion Sort
classInsertionSort {
/*Function to sort array using insertion sort*/
void sort(int arr[])
{
int n = arr.length;
for (inti = 1; i< n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 &&arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
/* A utility function to print array of size n*/
static void printArray(intarr[])
{
int n = arr.length;
for (inti = 0; i< n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
public static void main(String args[])
{
intarr[] = { 12, 11, 13, 5, 6 };
InsertionSortob = new InsertionSort();
ob.sort(arr);
printArray(arr);
}
}

Output:
2A.STACK DATA STRUCTURE USING CLASSES AND OBJECTS.
Program:
importjava.util.Stack;

class Main
{
public static void main(String[] args)
{
Stack<String> stack = new Stack<String>();

stack.push("A"); // Insert `A` into the stack


stack.push("B"); // Insert `B` into the stack
stack.push("C"); // Insert `C` into the stack
stack.push("D"); // Insert `D` into the stack

// prints the top of the stack (`D`)


System.out.println("The top element is " + stack.peek());

stack.pop(); // removing the top element (`D`)


stack.pop(); // removing the next top (`C)

// returns the total number of elements present in the stack


System.out.println("The stack size is " + stack.size());

// check if the stack is empty


if (stack.empty()) {
System.out.println("The stack is empty");
}
else {
System.out.println("The stack is not empty");
}
}
}
Output:
2B. QUEUE DATA STRUCTURE USING CLASSES AND OBJECTS.
Program:
importjava.util.LinkedList;
importjava.util.Queue;
publicclassQueueExample {

publicstaticvoidmain(String[] args)
{
Queue<Integer> q
= newLinkedList<>();

// Adds elements {0, 1, 2, 3, 4} to


// the queue
for(inti = 0; i< 5; i++)
q.add(i);

// Display contents of the queue.


System.out.println("Elements of queue "
+ q);

// To remove the head of queue.


intremovedele = q.remove();
System.out.println("removed element-"
+ removedele);

System.out.println(q);

// To view the head of queue


inthead = q.peek();
System.out.println("head of queue-"
+ head);

// Rest all methods of collection


// interface like size and contains
// can be used with this
// implementation.
intsize = q.size();
System.out.println("Size of queue-"
+ size);
}
}
Output:

.
3A.CHECK ADD OR EVEN USING CONSTRUCTOR
Program:
public class NumberChecker{
private int number;
public NumberChecker(int numbers){
this.number=number;
}
public boolean is Even(){
return number%2==0;
}
public boolen is odd(){
return num%2!=0;
}
public static void main(String[]args){
int num=7;
NumberChecker checker=new NumberChecker(num);
if(checker.isEven()){
System.out.println(num+”is even.”);
}else{
System.out.println(num+”is odd.”);
}
}}

Output:
7 is odd
3B.GENERATE PAYSLIP USING INHERITANCE
Program:
import java.util.*;
class employee
{
int empid;
long mobile;
String name, address, mailid;
Scanner get = new Scanner(System.in);
voidgetdata()
{
System.out.println("Enter Name of the Employee");
name = get.nextLine();
System.out.println("Enter Mail id");
mailid = get.nextLine();
System.out.println("Enter Address of the Employee:");
address = get.nextLine();
System.out.println("Enter employee id ");
empid = get.nextInt();
System.out.println("Enter Mobile Number");
mobile = get.nextLong();
}
void display()
{
System.out.println("Employee Name: "+name);
System.out.println("Employee id : "+empid);
System.out.println("Mail id : "+mailid);
System.out.println("Address: "+address);
System.out.println("Mobile Number: "+mobile);
}
}
class programmer extends employee
{
doublesalary,bp,da,hra,pf,club,net,gross;
voidgetprogrammer()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
voidcalculateprog()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROGRAMMER");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("PF:Rs"+pf);
System.out.println("HRA:Rs"+hra);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
classasstprofessor extends employee
{
doublesalary,bp,da,hra,pf,club,net,gross;
voidgetasst()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
voidcalculateasst()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSISTANT PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
classassociateprofessor extends employee
{
doublesalary,bp,da,hra,pf,club,net,gross;
voidgetassociate()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
voidcalculateassociate()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSOCIATE PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class professor extends employee
{
doublesalary,bp,da,hra,pf,club,net,gross;
voidgetprofessor()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
voidcalculateprofessor()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
/**
*
* @author CSE
*/
public class Salary {
/**
* @paramargs the command line arguments
*/
public static void main(String[] args) {
intchoice,cont;
do
{
System.out.println("PAYROLL");
System.out.println(" 1.PROGRAMMER \t 2.ASSISTANT PROFESSOR \t 3.ASSOCIATE
PROFESSOR \t 4.PROFESSOR ");
Scanner c = new Scanner(System.in);
choice=c.nextInt();
switch(choice)
{
case 1:
{
programmer p=new programmer();
p.getdata();
p.getprogrammer();
p.display();
p.calculateprog();
break;
}
case 2:
{
asstprofessorasst=new asstprofessor();
asst.getdata();
asst.getasst();
asst.display();
asst.calculateasst();
break;
}
case 3:
{
associateprofessorasso=new associateprofessor();
asso.getdata();
asso.getassociate();
asso.display();
asso.calculateassociate();
break;
}
case 4:
{
professor prof=new professor();
prof.getdata();
prof.getprofessor();
prof.display();
prof.calculateprofessor();
break;
}
}
System.out.println("Do u want to continue 0 to quit and 1 to continue ");
cont=c.nextInt();
}while(cont==1);
}
}

Output:
4.CALCULATE AREA USING ABSTRACT CLASS
Program:
Import java.util.*;
abstract class shape
{
inta,b;
abstract public void printarea();
}
class rectangle extends shape
{
publicintarea_rect;
@Override
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the length and breadth of rectangle");
a=s.nextInt();
b=s.nextInt();
area_rect=a*b;
System.out.println("Length of rectangle "+a +"breadth of rectangle "+b);
System.out.println("The area ofrectangle is:"+area_rect);
}
}
class triangle extends shape
{
doublearea_tri;
public void printarea()
{
Scanner s=new Scanner(System.in);System.out.println("enter the base and height of triangle");
a=s.nextInt();
b=s.nextInt();
System.out.println("Base of triangle "+a +"height of triangle "+b);
area_tri=(0.5*a*b);
System.out.println("The area of triangle is:"+area_tri);
}
}
class circle extends shape
{
doublearea_circle;
@Override
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the radius of circle");
a=s.nextInt();
area_circle=(3.14*a*a);
System.out.println("Radius of circle"+a);
System.out.println("The area of circle is:"+area_circle);
}
}
public class Shapeclass {
/**
* @paramargs the command line arguments
*/
public static void main(String[] args) {
rectangle r=new rectangle();
r.printarea();triangle t=new triangle();
t.printarea();
circle r1=new circle();
r1.printarea();
// TODO code application logic here
}

Output:
5A.ABSTRACT CLASS
Program:
interface Shape
{
void input();
void area();
}
class Circle implements Shape
{
int r = 0;
double pi = 3.14, ar = 0;
@Override
public void input()
{
r = 5;
}
@Override
public void area()
{
ar = pi * r * r;
System.out.println("Area of circle:"+ar);
}
}
class Rectangle extends Circle
{
int l = 0, b = 0;
doublear;
public void input()
{
super.input();
l = 6;
b = 4;
}
public void area()
{
super.area();
ar = l * b;
System.out.println("Area of rectangle:"+ar);
}
}
public class Demo {
public static void main(String[] args) {
Rectangle obj = new Rectangle();
obj.input();
obj.area();
}
}
Output:
5B.CALCULATE AREA OF SQUARE AND RECTANGLE USING
INTERFACE
Program:
interface Shape{
double calculateArea();
}
class Square implements Shape{
private double side;
public Square(double side){
this.side=side;
}
@Override
public double calculateArea(){
return side*side;
}
}
class Rectangle implements Shape{
private double length;
private double width;
public Rectangle(double length,double width){
this.length=length;
this.width=width;
}
@Override
public double calculateArea(){
return length*width;
}
}
public class Main{
public static void main(String[] args){
Square sqare=new Square(5.0);
Rectangle rectangle=new Rectangle(4.0,6.0);
System.out.println(“Area of the square:”+square.calculateArea());
System.out.println(“Area of the rentangle:”+rectangle.calculateArea());
}
}

Output:
Area of square:25.0
Area of rectangle:24.0
5C.METHOD OVERLOADING
Program:
//Define the interface with add and sub methods
interface Calculator{
double add(double num1,double num2);
double sub(double num1,double num2);
}
//Create a class that implements the Calculator interface
class Calculatorimplementation implements Calculator{
@Override
public double add(double num1,double num2){
return num1+num2;
}
@Override
public double sub(double num1,doublenum2){
return num1-num2;
}
}
public class Main{
public static void main(String[]args){
Calculator calculator=new CalculatorImplementation();
double resultAdd=calculator.add(5.0,3.0);
double resultSub=calculator.sub(5.0,3.0);
System.out.println(“Addition result:”+resultAdd);
System.out.println(“Subtractor result:”+resultSub);
}
}
Output:
Addition result:8.0
Subtraction result:2.0
6.USER DEFINED EXCEPTION HANDLING
Program:
import java.util.Scanner;
classNegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
returnmsg;
}
}
public class Userdefined {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.print("Enter Amount:");
int a=s.nextInt();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
System.out.println("Amount Deposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
}

Output:
7.MULTITHREAD APPLICATION
Program:
import java.util.*;
class even implements Runnable
{
publicint x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x * x); }
}
class odd implements Runnable
{
publicint x;
public odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x * x); }
}
class A extends Thread
{
public void run()
{
intnum = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num));
t1.start();
}
else
{
Thread t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class multithreadprog {
public static void main(String[] args) {
A a = new A();
a.start();
}
}

Output:
8.PERFORM FILE OPERATION.
Program:
import java.io.*;
importjava.util.*;
classfiledemo
{
public static void main(String args[])
{
String filename;
Scanner s=new Scanner(System.in);
System.out.println("Enter the file name ");
filename=s.nextLine();
File f1=new File(filename);
System.out.println("*****************");
System.out.println("FILE INFORMATION");
System.out.println("*****************");
System.out.println("NAME OF THE FILE "+f1.getName());
System.out.println("PATH OF THE FILE "+f1.getPath());
System.out.println("PARENT"+f1.getParent());
if(f1.exists())
System.out.println("THE FILE EXISTS ");
else
System.out.println("THE FILE DOES NOT ExISTS ");
if(f1.canRead())
System.out.println("THE FILE CAN BE READ ");
else
System.out.println("THE FILE CANNOT BE READ ");
if(f1.canWrite())
System.out.println("WRITE OPERATION IS PERMITTED");
else
System.out.println("WRITE OPERATION IS NOT PERMITTED");
if(f1.isDirectory())
System.out.println("IT IS A DIRECTORY ");
else
System.out.println("NOT A DIRECTORY");
if(f1.isFile())
System.out.println("IT IS A FILE ");
else
System.out.println("NOT A FILE");
System.out.println("File last modified "+ f1.lastModified());
System.out.println("LENGTH OF THE FILE "+f1.length());
System.out.println("FILE DELETED "+f1.delete());
}
}

Output:
9.FINDING MAXIMUM VALUE USING GENERICS
Program:
classMyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] o)
{
vals = o;
}
public T min()
{
T v = vals[0];
for(int i=1; i <vals.length; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(int i=1; i <vals.length;i++)
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
}
}
classgendemo
{public static void main(String args[])
{
int i;
Integer inums[]={10,2,5,4,6,1};
Character chs[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
MyClass<Integer>iob = new MyClass<Integer>(inums);
MyClass<Character> cob = new MyClass<Character>(chs);
MyClass<Double>dob = new MyClass<Double>(d);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
System.out.println("Max value in chs: " + dob.max());
System.out.println("Min value in chs: " + dob.min());
}
}

Output:
10A.JAVA FX CONTROL
Program:
package buttonexample3;
importjava.awt.*;
importjava.awt.event.*;
public class ButtonExample3 {
public static void main(String[] args) {
// create instance of frame with the label
Frame f = new Frame("Button Example");
finalTextFieldtf=new TextField();
tf.setBounds(50,50, 150,20);
// create instance of button with label
Button b=new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
tf.setText("Welcome to Javatpoint.");
}
});
// adding button the frame
f.add(b);
// adding textfield the frame
f.add(tf);
// setting size, layout and visibility
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:
10B.MENUS
Program:

import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output:
11.MINI PROJECT –SNAKE GAME
Program:
public class SnakeGame {
public static void main(String[] args) {
newGameFrame();
}
}
//*****************************************
import javax.swing.JFrame;
public class GameFrame extends JFrame{
GameFrame(){
this.add(new GamePanel());
this.setTitle("Snake");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack(); this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
//*****************************************
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
importjava.util.Random;
public class GamePanel extends JPanel implements ActionListener{
static final int SCREEN_WIDTH = 1300;
static final int SCREEN_HEIGHT = 750;
static final int UNIT_SIZE = 50;
static final int GAME_UNITS =
(SCREEN_WIDTH*SCREEN_HEIGHT)/(UNIT_SIZE*UNIT_SIZE);
static final int DELAY = 175;
finalint x[] = new int[GAME_UNITS];
finalint y[] = new int[GAME_UNITS];
intbodyParts = 6;
intapplesEaten;
intappleX;
intappleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random;
GamePanel(){
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
newApple();
running = true;
timer = new Timer(DELAY,this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if(running) {
/*for(int i=0;i<SCREEN_HEIGHT/UNIT_SIZE;i++) {
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE); } */
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
for(int i = 0; i<bodyParts;i++) {
if(i == 0) { g.setColor(Color.green);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
else {
g.setColor(new Color(45,180,0));
//g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 40));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics.stringWidth("Score:
"+applesEaten))/2, g.getFont().getSize());
}
else { gameOver(g);
}
}
public void newApple(){
appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;
}
public void move(){
for(int i = bodyParts;i>0;i--) {
x[i] = x[i-1]; y[i] = y[i-1];
}
switch(direction) {
case 'U':
y[0] = y[0] - UNIT_SIZE;
break;
case 'D':
y[0] = y[0] + UNIT_SIZE;
break;
case 'L':
x[0] = x[0] - UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++; applesEaten++; newApple();
}
}
public void checkCollisions() {
//checks if head collides with body
for(int i = bodyParts;i>0;i--) {
if((x[0] == x[i])&& (y[0] == y[i])) {
running = false;
}
}
//check if head touches left border
if(x[0] < 0) {
running = false;
}
//check if head touches right border
if(x[0] > SCREEN_WIDTH) {
running = false;
}
//check if head touches top border
if(y[0] < 0) {
running = false;
}
//check if head touches bottom border
if(y[0] > SCREEN_HEIGHT) {
running = false;
}
if(!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
//Score g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 40));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics1.stringWidth("Score:
"+applesEaten))/2, g.getFont().getSize());
//Game Over text g.setColor(Color.red);
g.setFont( new Font("Ink Free",Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("Game Over", (SCREEN_WIDTH - metrics2.stringWidth("Game Over"))/2,
SCREEN_HEIGHT/2);
}
@Override public void actionPerformed(ActionEvent e) {
if(running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter{
@Override public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
caseKeyEvent.VK_LEFT:
if(direction != 'R') {
direction = 'L';
}
break;
caseKeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
caseKeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
caseKeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
}
}
}
}
//*****************************************
Output:

You might also like