0% found this document useful (0 votes)
46 views

Code

The document contains code examples for implementing different data structures in Java including: 1. A CreditCard class that represents a basic credit card with fields for customer, bank, account, limit, and balance. It includes methods for charging, making payments, and a constructor. 2. A PredatoryCreditCard class that extends CreditCard and adds interest charging functionality. 3. A Game class that stores high scores using a ScoreBoard with a fixed capacity. It includes classes for GameEntry and methods for adding, removing, and searching scores. 4. Code for a SinglyLinkedList that implements a basic linked list with methods for adding nodes to the front and back, and printing the list.

Uploaded by

kristi spahi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Code

The document contains code examples for implementing different data structures in Java including: 1. A CreditCard class that represents a basic credit card with fields for customer, bank, account, limit, and balance. It includes methods for charging, making payments, and a constructor. 2. A PredatoryCreditCard class that extends CreditCard and adds interest charging functionality. 3. A Game class that stores high scores using a ScoreBoard with a fixed capacity. It includes classes for GameEntry and methods for adding, removing, and searching scores. 4. Code for a SinglyLinkedList that implements a basic linked list with methods for adding nodes to the front and back, and printing the list.

Uploaded by

kristi spahi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Kodi – Struktura të dhënash bazë

Code – Fundamental data structures

1. CreditCard.java
public class CreditCard {
String customer;
String bank;
String account;
int limit;
double balance;

public CreditCard(String cust, String bk, String acnt, int lim, double
initialBal) {
customer = cust;
bank = bk;
account = acnt;
limit = lim;
balance = initialBal;
}

public boolean charge(double price) {


if (price + balance > limit)
return false;

// at this point, the charge is successful


balance += price;
return true;
}

public void makePayment(double amount) {


balance -= amount;
}
}

2. PredatoryCreditCard.java
public class PredatoryCreditCard extends CreditCard {
// Additional instance variable
private double apr; // annual percentage rate
// Constructor for this class
public PredatoryCreditCard(String cust, String bk, String acnt, int
lim, double initialBal, double rate)
{
// initialize superclass attributes
super(cust, bk, acnt, lim, initialBal);
apr = rate;
}
// A new method for assessing monthly interest charges
public void processMonth( ) {
if (balance > 0) {
double monthlyFactor = Math.pow(1 + apr, 1.0/12);
balance *= monthlyFactor;

}
}
// Overriding the charge method defined in the superclass
public boolean charge(double price) {
// call inherited method
boolean isSuccess = super.charge(price);
if (!isSuccess)
// assess a $5 penalty
balance -= 5;
return isSuccess;
}
}

MainCredit.java
public class MainCredit {
public static void main(String[] args)
{
CreditCard CC1=new CreditCard("Alba","ABI","123",500,100);
if(CC1.charge(200))
{
System.out.println("New charge done successfully");
}

CreditCard CC2=new PredatoryCreditCard("Alba","ABI","123",500,100,2);


if(!CC2.charge(600))
{
System.out.println("Limit exceeded.");
System.out.println("Your new balance is "+CC2.balance);
}
}
}

Game (GameEntry.java, MainGame.java, ScoreBoard.java)


GameEntry.java
package Game;

public class GameEntry {


private String name; // name of the person earning this score
private int score; // the score value

/** Constructs a game entry with given parameters.. */


public GameEntry(String n, int s) {
name = n;
score = s;
}
/** Returns the name field. */
public String getName( ) {
return name;
}

/** Returns the score field. */


public int getScore( ) {
return score;
}

/** Returns a string representation of this entry. */


//Overrides the toString method of the class Object
public String toString( ) {
return "(" + name + ", " + score + ")";
}
}

ScoreBoard.java
package Game;

/** Class for storing high scores in an array in nondecreasing order. */


public class ScoreBoard {
private int numEntries = 0; // number of actual entries
private GameEntry[] board; // array of game entries

/** Constructs an empty scoreboard with the given capacity for


storing entries. */
public ScoreBoard(int capacity) {
board = new GameEntry[capacity];
}

public void add(GameEntry e) {


int newScore = e.getScore( );

// is the new entry e really a high score?


if (numEntries < board.length || newScore > board[numEntries-
1].getScore( )) {
if (numEntries < board.length)
// no score drops from the board
numEntries++;
// so overall number increases

// shift any lower scores rightward to make room for the new entry
int j = numEntries - 1;
while (j > 0 && board[j-1].getScore( ) < newScore) {
board[j] = board[j-1];
// shift entry from j-1 to j
j--; // and decrement j
}
board[j] = e; // when done, add new entry
}
}

/** Remove and return the high score at index i. */


public GameEntry remove(int i) throws IndexOutOfBoundsException {
if (i < 0 || i >= numEntries)
throw new IndexOutOfBoundsException("Invalid index: " + i);
GameEntry temp = board[i]; // save the object to be removed
for (int j = i; j < numEntries - 1; j++)
// count up from i (not down)
board[j] = board[j+1];
// move one cell to the left
board[numEntries-1 ] = null;
// null out the old last score
numEntries--;

return temp;
// return the removed object
}

public void BoardString( ) {


for(int i=0;i<numEntries;i++)
{
System.out.println(" "+board[i]);
}
}
// You search a specific name
//You can give as parameter the index to be searched
public int Search(String _name){
for(int i=0;i<numEntries;i++){
if(board[i].getName()==_name)
return i;
}
System.out.println("Couldn't find the name");
return -1;
}
}

MainGame.java
package Game;

public class MainGame {


public static void main(String[] args)
{
GameEntry G1 = new GameEntry("Evis",100);
GameEntry G2 = new GameEntry("Anila",20);
GameEntry G3 = new GameEntry("Dea",10);
System.out.println("Name of the first player is:"+
G1.getName());
System.out.println("Score of the second player is:"+
G2.getScore());
ScoreBoard S = new ScoreBoard(3);
S.add(G1);
S.add(G2);
S.add(G3);
S.BoardString();

System.out.println();
S.remove(2);
//S.search(2); //printimi i objektit ne indexin 2
//S.search(10); //10 jane piket .Ka apo jo lojtare me 10 pike.
//Nese po do printoni objektin (Emrin,Piket)
//Nese jo do printoni nuk gjendet.
S.BoardString();
}
}
SinglyLinkedList (LinkedList.java, SinglyLinkedList.java)
LinkedList.java
package SinglyLinkedList;

//Insertion in Linked List


class LinkedList
{
Node head;

class Node
{
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}

// Inserts a new Node at front of the list.


public void addFirst(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}

// Appends a new node at the end.


public void addLast(int new_data)
{

Node new_node = new Node(new_data);


if (head == null)
{
head = new Node(new_data);
return;
}

new_node.next = null;

Node last = head;


while (last.next != null)
last = last.next;

last.next = new_node;
return;
}

//Prints contents of linked list


public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
}

// Main part to execute the above functions


public static void main(String[] args)
{
// Empty list
LinkedList llist = new LinkedList();

//Linked list becomes 6->Null


llist.addLast(6);

// Linked list becomes 7->6->NUll


llist.addFirst(7);

// Linked list becomes 1->7->6->NUll


llist.addFirst(1);

// Linked list becomes 1->7->6->4->NUll


llist.addLast(4);

System.out.println("\nCreated Linked list is: ");


llist.printList();
}
}

SinglyLinkedList.java
package SinglyLinkedList;

public class SinglyLinkedList<E> {

//---------------- nested Node class ----------------


private static class Node<E> {
private E element;
// reference to the element stored at this node
private Node<E> next;
// reference to the subsequent node in the list
public Node(E e, Node<E> n) {
element = e;
next = n;
}
public E getElement() {
return element;
}
public Node<E> getNext( ) {
return next;
}

public void setNext(Node<E> n) {


next = n;
}
}
//----------- end of nested Node class -----------

// instance variables of the SinglyLinkedList


private Node<E> head = null;
private Node<E> tail = null;
private int size = 0;
public SinglyLinkedList( ) { }

// access methods
public int size() {
return size;
}
public boolean isEmpty( ) {
return size == 0;
}
public E first() {
if (isEmpty( ))
return null;
return head.getElement( );
}
public E last() {
if (isEmpty( ))
return null;
return tail.getElement( );
}

// update methods
public void addFirst(E e) {
head = new Node<>(e, head);
if (size == 0)
tail = head;
size++;
}

public void addLast(E e) {


Node<E> newest = new Node<>(e, null);
if (isEmpty( ))
head = newest;
else
tail.setNext(newest);
tail = newest;
size++;
}

public E removeFirst( ) {
// removes and returns the first element
if (isEmpty( ))
return null;
E answer = head.getElement( );
head = head.getNext( );
size--;
if (size == 0)
tail = null;
return answer;
}
}

You might also like