How do you implement Comparable in this situation? - java

I've looked up examples as to how Comparable works and I somewhat understand how it would work but I don't know how I would use it in this situation.
I have an ArrayObject class implements Comparable and imported java.util.*; I also have an ArrayObjectDriver class that is a main method that calls upon methods I've coded in the ArrayObject class. One of the methods that it has to be able to do is to sort the array of objects in the main method. I know you have to use something with .compareTo but I'm not sure how I would do that in the ArrayObject class and call on it in the driver.
EDIT: ArrayObject code
public class ArrayObject implements Comparable
{
private Object[] arr;
private int actualSize;
ArrayObject()
{
arr = new Object[10];
actualSize = 0;
}
ArrayObject(int size)
{
arr = new Object[size];
actualSize = 0;
}
public void add(Object obj)
{
if(actualSize>=arr.length)
expandArray();
arr[actualSize]=obj;
actualSize++;
}
public void expandArray()
{
int newSize = arr.length*2;
Object[] biggerList = new Object[newSize];
for(int i=0; i<arr.length; i++)
{
biggerList[i] = arr[i];
}
arr = biggerList;
}
public void add(Object obj, int index)
{
if(index<actualSize)
{
shiftRight(index);
arr[index]=obj;
actualSize++;
}
// index is between [0 and actualSize)
}
private void shiftRight(int start)
{
for(int i=actualSize; i>start; i--)
{
arr[i] = arr[i-1];
}
arr[start]=null;
}
private void shiftLeft(int start)
{
for(int i=start; i<actualSize-1; i++)
{
arr[i] = arr[i+1];
}
arr[actualSize-1]=null;
}
public Object remove(int index)
{ // returning the object you are removing
// ("the", "is", "are")
if(index>=0&&index<actualSize)
{
Object obj = arr[index];
arr[index] = null;
// arr[index] = arr[actualSize-1];
// what to do about the null?
// Shift to the left by one
shiftLeft(index);
actualSize--;
// ("the", null, "are")
return obj;
}
return null;
}
public Object get(int index)
{
if(index>=0&&index<actualSize)
return arr[index];
return null;
}
public int sizeOfContainer()
{
return arr.length;
}
public int items()
{
return actualSize;
}
public boolean searchArray(Object obj)
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
return true;
}
return false;
}
public int findObject(Object obj)
{
if(searchArray(obj))
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
return i;
}
}
return -1;
}
public boolean isItEmpty()
{
if(actualSize == 0)
return true;
return false;
}
public int removeSearch(Object obj)
{
for(int i=0; i<actualSize; i++)
{
if(arr[i].equals(obj))
{
remove(i);
return i;
}
}
return -1;
}
public void clearArray()
{
for(int i=0; i<actualSize; i++)
arr[i] = remove(i);
}
public void printArr()
{
System.out.println("Array Size: " + actualSize);
for(int i=0; i<actualSize; i++)
{
System.out.println(arr[i]);
}
}
}
ArrayObjectDriver code
public class ArrayObjectDriver
{
private static Scanner scanner;
public static void main(String[] args)
{
scanner = new Scanner(System.in);
ArrayObject array = new ArrayObject();
int selection = selectionMenu();
while(selection > 0)
{
if(selection == 1)
{
System.out.println("Enter your object: ");
String str = scanner.next();
array.add(str);
}
else if(selection == 2)
{
System.out.println("Enter your object: ");
String str = scanner.next();
System.out.println("Enter location: ");
int n = scanner.nextInt();
array.add(str, n);
}
else if(selection == 3)
{
System.out.println("Enter location: ");
int n1 = scanner.nextInt();
array.remove(n1);
}
else if(selection == 4)
{
System.out.println("Enter object: ");
String str = scanner.next();
int i = array.removeSearch(str);
System.out.println("Object removed at index " + i);
}
else if(selection == 5)
{
array.clearArray();
System.out.println("Cleared Array");
}
else if(selection == 6)
{
System.out.println("Enter object: ");
String str = scanner.next();
boolean result = array.searchArray(str);
System.out.println("The object was found: " + result);
}
else if(selection == 7)
{
boolean result = array.isItEmpty();
System.out.println("It is empty: + result);
}
else if(selection == 8)
{
array.expandArray();
int i = array.sizeOfContainer();
System.out.println("The new size of the array is: " + i);
}
else if(selection == 9)
{
System.out.println("Enter object: ")
String str = scanner.next();
int i = array.findObject(str);
System.out.println("The object was found at index " + i);
}
else if(selection == 10)
array.printArr();
else if(selection == 11)
{
}
else if(selection == 12)
System.exit(0);
System.out.println("");
selection = selectionMenu();
}
}
private static int selectionMenu()
{
System.out.println("Menu: ");
System.out.println("1. Add object to the end of the list");
System.out.println("2. Add object at a specific location");
System.out.println("3. Remove specific object at a location");
System.out.println("4. Remove specific object that matches name");
System.out.println("5. Empty the array");
System.out.println("6. See if the array contains a certain object");
System.out.println("7. See if the array is empty");
System.out.println("8. Expand your array");
System.out.println("9. Search for an item");
System.out.println("10. Print array");
System.out.println("11. Sort array");
System.out.println("12. Exit");
System.out.println("Enter option: ");
int optionNumber = scanner.nextInt();
return optionNumber;
}
}

Just make a sort method in your ArrayObject class and you can call that when user enters 11.
In ArraysObject:
public void sort(){
Arrays.sort(arr); //This is all you have to call to sort your array arr
}
In your ArrayObjectDriver:
else if(selection == 11)
{
array.sort();
}
The Arrays class has useful methods for searching, manipulating, and sorting arrays including Arrays.sort and Arrays.binarySearch.

Related

Circular queue array implementation

Im trying to create a waiting list which will hold names of customers in a static array when the main array is full.and When the main array gets an EMPTY slot the first customer in the waiting list array will fill up the EMPTY slot of main array and the added element will be removed Im trying to create this using circular queue implementation.following the FIFO(First in first out) system
This is the circular queue implementation I have come up with
public class CQueue {
int SIZE = 4;
int front, rear;
int items[] = new int[4];
void initialize (String[]task) {
for (int i = 0; i < task.length; i++) {
task[i] = "FULL";
}
}
CQueue() {
front = -1;
rear = -1;
}
boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
if (front == rear + 1) {
return true;
}
return false;
}
boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}
void enQueue(int element) {
if (isFull()) {
System.out.println("Queue is full");
} else {
if (front == -1)
front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
System.out.println("Inserted " + element);
}
}
int deQueue() {
int element;
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else {
front = (front + 1) % SIZE;
}
return (element);
}
}
void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Front -> " + front);
System.out.println("Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE)
System.out.print(items[i] + " ");
System.out.println(items[i]);
System.out.println("Rear -> " + rear);
}
}
This the delete method which will take user input to delete the element from task array and add the first come element of queue.
void deleteArr(String task[]) {
CQueue q = new CQueue();
int NUM;
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer num to delete : ");
NUM = sc.nextInt()-1;
task[NUM] = "EMPTY";
int element = items[front];
task[NUM]=Integer.toString(element);
q.deQueue();
q.display();
}
The main method
public static void main(String[] args) {
int k =1;
String task[] = new String[12];
CQueue q = new CQueue();
q.initialize(task);
q.display();
for (int i = 0; i < task.length; i++) {
if (task[i].equals("FULL")) {
q.enQueue(k);
k++;
}
}
while (true) {
q.deleteArr(task);
for (int j = 0; j < task.length; j++) {
System.out.println(task[j]);
}
}
}
I am stuck on how to add the queue element to the task array when a task array is deleted
I'd recommend you to check if front>=0 in deteleArr function. Also you should use the queue instance defined in main, and not a new instance:
void deleteArr(String task[]) {
int NUM;
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer num to delete : ");
NUM = sc.nextInt()-1;
task[NUM] = "EMPTY";
if(front>=0) {
task[NUM]=Integer.toString(items[front]);
}
this.deQueue();
}
If you want, you can use the following display queue function:
void display() {
int i;
System.out.println("Print queue");
System.out.println("===========");
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Front -> " + front);
for (i = front; i <= rear; i++) {
System.out.println("item["+i+"]: " +items[i]);
}
System.out.println("Rear -> " + rear);
}
System.out.println("============");
}
And you can use this another function to display the task array:
public static void printTaskArray(String task[]) {
System.out.println("Print task[]");
System.out.println("============");
if (task.length==0) {
System.out.println("Empty task");
} else {
for (int j = 0; j < task.length; j++) {
System.out.println("task["+j+"]: "+task[j]);
}
}
System.out.println("============");
}
With this encapsulation you can change your main as follows:
public static void main(String[] args) {
int k =1;
String task[] = new String[12];
CQueue q = new CQueue ();
q.initialize(task);
printTaskArray(task);
q.display();
for (int i = 0; i < task.length; i++) {
if (task[i].equals("FULL")) {
q.enQueue(k);
k++;
}
}
printTaskArray(task);
q.display();
while (true) {
q.deleteArr(task);
printTaskArray(task);
q.display();
}
}
I hope this help you.

Can't "new object" for generic class with type casting

This code is for learning generic class and stack operation.
but it has some error about declare variable type
package lab11_2_590510535;
import java.util.Scanner;
class Queue <TYPE>{
private int count;
private int front;
private int rear;
private int n;
private Object [] item;
private TYPE queueFront;
static void pl(Object a){System.out.println(a);}
static void p(Object a){System.out.print(a);}
Queue(int x){
n = x;
item = new Object[n];
front = 0;
rear = -1;
count = 0;
}
public boolean isEmpty(){
for(int i = 0 ; i<item.length ; i++){
if(item[i] != null){return false;}
}
return true;
}
public boolean isFull(){
if(item[item.length] != null){return true;}
else{return false;}
}
public void enqueue(TYPE v){
if(!isFull()){
if(rear < n-1){
rear++;
item[rear] = v;
count++;
}
}else{pl("Queue is Full.");}
}
public TYPE dequeue(){
if(!isEmpty()){
queueFront = item[front];
front++;
count++;
}else{p("Queue is empty.");}
return queueFront;
}
public void show(){
for(int i = 0 ; i <item.length ; i++){
if(item[i] != null){p(item[i] + ", ");}
}
}
public class Lab11_2_590510535 {
static void pl(Object a){System.out.println(a);}
static void p(Object a){System.out.print(a);}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner keyboard = new Scanner(System.in);
char choice;
int N;
p("Enter N: ");
N = keyboard.nextInt();
p("Choice input type; int(1) , char(2): ");
choice = keyboard.next().charAt(0);
if(choice == '1'){Queue <Integer> q = new Queue(N);}
else if(choice == '2'){Queue <Character> q = new Queue(N);}
do{
pl("1) enqueue"); pl("2) dequeue"); pl("3) show"); pl("4) exit");
p("Enter function number : ");
choice = keyboard.next().charAt(0);
if(choice == '1'){
p("Enter data: ");
Object s = keyboard.next();
q.enqueue(s);
}
else if(choice == '2'){Object s = q.dequeue();
pl(s);
}
else if(choice == '3'){q.show();}
}while(choice != '4');
}
}
1.After user input choice and I create generic object with type casting in do...while loop it can't find "q".
2.In public TYPE dequeue() method line "queueFront = item[front];" Object can't be convert to TYPE ,how can I fix it.
Try to change private Object [] item to private TYPE [] item. Also you will need to know how to create a generic array for your example:
How to create a generic array?
How to create a generic array in Java?
You will need to change item = new Object[n]; to item = (TYPE[]) new Object[n];
However you should avoid creating generic types and instead you should inject them or use a factory to create them.

How to Collect all scores in Blackjack and record games in a table in java?

I need help with creating a table in for my blackjack, that records all games and also shows the average score of all games.I Have my code but im stuck on what to do to fix the code. Here are all the codes that im working with. Here is an example of what the output should look like:Pic of how output should look like
import java.util.*;
class Blackjack{
public static void main (String[] arg) {
Deck d = new Deck(); d.shuffle();
Hand h = new Hand();
//Score s = new Score(); //added for bonus
System.out.println(d);
System.out.println(d.hit());
System.out.println( d.decode(d.hit()) );
h.add(5);
h.add(10);
System.out.println(h.display());
while(true) {
System.out.print("Enter (n)ew hand, (h)it, or (q)uit: ");
Scanner scan = new Scanner (System.in);
// these variables are for collecting the information for the Score
int [] line = new int [5]; //added for Bonus
int handScore = 0; //added for Bonus
char c = scan.next().charAt(0);
if (c == 'n' || c == 'N') {
System.out.println(c);
h.reset();
if (d.currentIndex < 51){
int card= d.hit(); h.add(card);
card= d.hit(); h.add(card);
h.display();
System.out.println();
} else if (d.currentIndex > 51) {
System.out.println("--- NO CARDS LEFT ON DECK ---");
System.out.println();
break;
} else {
System.out.println("-- NOT ENOUGH CARDS LEFT ON DECK--");
System.out.println();
break;
}
} else if (c == 'h' || c == 'H') {
System.out.println(c);
if (d.currentIndex < 52){ //must be 52
int handValue = h.scoreInHand() ;
if (handValue > 21) { //already busted
System.out.println("--- GET A NEW HAND --- ");
System.out.println();
} else if (handValue == 21) {//already blackjack
System.out.println("--- BlackJack --- ");
System.out.println();
} else if (h.firstIndex > 4 ) {
System.out.println( "-- ALREADY 5 CARDS IN HAND ---");
h.display();
System.out.println( "--- GET A NEW HAND ---");
System.out.println();
} else if (h.firstIndex == 0) {
System.out.println("--- GET A NEW HAND FIRST ---");
System.out.println();
} else {
int card= d.hit(); h.add(card);
h.display(); System.out.println();
}
} else { // > or = 52
System.out.println("----- NO CARDS LEFT ON DECK -----");
System.out.println();
break;
}//end if (d.firstIndex < 52
} else if (c == 'q' || c == 'Q') {
System.out.println(c);
//same as the if(c == n), so it can collect the last game.
break;
}
} //while
//prints the scores of the games the user played while the game was run.
//System.out.print(s.display());System.out.println(); //added for Bonus
System.out.println("BYE!");
}//end main
}
class Hand{
private int []Hand;
public int firstIndex;
Hand(){
Hand=new int[5];
for (int i=0; i<Hand.length; i++)
Hand[i]=-1;
firstIndex=0;
}
public String display(){
String s="";
String empty="Hand is empty";
for (int i=0; i<firstIndex;i++)
s=s+" "+decode(Hand[i]);
if (s.length()==0)
s= empty;
String sih="";
int sihand= scoreInHand();
if(sihand>0&&sihand<21)
sih=""+sihand;
else if(sihand==21&&firstIndex==2)
sih="blackjack";
else if (sihand==21&&firstIndex>2)
sih=""+sihand;
else
sih="BUST";
System.out.println(s+"\n"+sih);
return s.trim();
}
public void reset(){
for (int i=0; i<Hand.length;i++)
Hand[i]=-1;
firstIndex=0;
}
public void add(int card){
Hand[firstIndex]=card;
firstIndex++;
}
public String decode2(int value){
String code=""+"HCDS".charAt(value/13)
+"23456789TJQA".charAt(value%13);
return code;
}
public String decode(int value){
String[] pattern={"Heart","Clubs","Diamond","Spades"};
String[] num={"two","three","four","five","six","seven","eight","nine","ten","jack","queen","king","ace"};
return num[value%13]+ " of " + pattern[value/13];
}
public int scoreInHand(){
int[] s={2,3,4,5,6,7,8,9,10,10,10,10};
boolean firstAce=true;
int value=0;
int sum=0;
for (int i=0; i<firstIndex; i++)
{
value=Hand[i]%13;
if (value==12)
{
if (firstAce)
{
value=11;
firstAce=false;
}
else
value=1;
}
else
value=s[value];
sum=sum+value;
}
return sum;
}
public String toString{
String s="";
for (int i=0; i<5; i++)
{
if (i<firstIndex)
s=s+" | " + decode2(Hand[i])+" ";
else
s=s+" ";
}
s=s+firstIndex;
return s;
}
}//(2,3,4,5,6,7,8,9,10,10,10,10,11)
class Deck{
private int[] cards;
public int currentIndex;
Deck(){
currentIndex=0;
cards=new int[52];
for (int i=0; i<cards.length; i++)
cards[i]=i;
}
public String toString(){
String s="";
for (int i=currentIndex;i<cards.length; i++)
{
/* s=s+" "+cards[i];*/
String code=decode(cards[i]);
s=s+" "+code;
}
return s;
}
public String decode(int value)
{
String code=""+"HCDS".charAt (value/13)
+"23456789TJQKA".charAt(value%13);
return code;
}
public void shuffle(){
int j=0;
for (int i=0;i<cards.length; i++)
{
j=(int)(52*Math.random());
swap(i,j);
}
}
public void swap(int i, int j){
int temp=cards[i];
cards[i]=cards[j];
cards[j]=temp;
}
public int hit(){
int i=cards[currentIndex];
currentIndex++;
return i;
}
}
class Score extends Deck{
private String [] cuts=new String [26];
private int gfirstIndex;
Score(){
cuts=new String[26];
gfirstIndex=0;
}
public void markScore(Hand h, int score)
{
String s="";
char fi;
String hand=h.toString();
int firstIndex;
fi=hand.charAt(hand.length()-1);
firstIndex=fi-'0';
hand=hand.substring(0,hand.length()-1);
s=s+" | "+(gfirstIndex+1)+(((gfirstIndex+1)<10)?" ":" ")|;
s=s+hand+" ";
s=s+"(score="+score+")";
if (score>21)
s=s+"(BUSTS)";
else if (score==21&&firstIndex==2)
s=s+"(BLACKJACK)";
cuts[gfirstIndex]=s;
gfirstIndex++;
}
}

quadratic probing hash table

Hellow, For some off reason I cannot get my hash table to fill with the items and keys when I insert. It seems like it is being added when run through the driver, but nothing is stored, and there are absolutely no error messages.
I am suppose to create a hash table that utilizes quadratic probing. I am suppose to count the number of transversals which cannot be > 20.
Here is the code:
public class HashTable {
String[] table;
String[] keys;
int currentSize, maxSize, numOfEntries;
int traverse = 0;
double capacity;
public HashTable(int size, double load){
if(size <= 0){
System.out.println("Size must be greater then 0");
}
else if(load < 0 || load > 1){
System.out.println("Load must be between 0 and 1. EX: 0.75");
}else{
this.currentSize = 0;
table = new String[size];
keys = new String[size];
this.capacity = load * size;
this.maxSize = size;
}
}
public int hash(String num){
return (2 * Integer.parseInt(num) + 5) % table.length;
}
public int getLength(){
return table.length;
}
public int getMaxSize(){
return maxSize;
}
public int probe(String num){
int temp = hash(num);
int calc = 0;
numOfEntries = 0;
while(table[temp] != null){
traverse++;
temp = (int)((temp + (float)calc/2 + (float) (calc * calc)) % maxSize);
calc++;
numOfEntries++;
}
if(traverse >= 20){
System.out.println("Insert Failed : Reached 20 Traversal Limit!");
return 20;
}
return temp;
}
public void resize(){
String [] tempTable = table;
if(table.length >= capacity){
table = new String[tempTable.length * 2];
for(int i = 0; i < tempTable.length; i++){
if(tempTable[i] != null){
insert(tempTable[i]);
}
}
}
}
public void insert(String num){
int temp = probe(num);
table[temp] = num;
currentSize++;
if(currentSize >= capacity){
resize();
}
}
public String searchKey(String key){
String temp = "";
numOfEntries = 0;
for(int i = 0; i < keys.length; i++){
if(key == keys[i]){
temp = table[i];
numOfEntries++;
break;
}
numOfEntries++;
}
if(temp == ""){
System.out.println("No items that match that key!");
}
return temp;
}
public int numOfEntries(){
return numOfEntries;
}
public void print(){
System.out.println("Key\t:\tValue");
for(int i = 0; i < table.length; i++){
if(keys[i] != null){
System.out.println(keys[i] + "\t:\t" + table[i]);
}
}
System.out.println();
}
}
Here is the Driver:
import java.util.*;
public class HashTableDriver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Table Size:\t");
int size = scan.nextInt();
System.out.println("Enter Load Factor (Between 0 and 1");
double load = scan.nextDouble();
int temp = 0;
HashTable table = new HashTable(size,load);
System.out.println(table.getLength());
System.out.println(table.getMaxSize());
while(temp != 4){
System.out.println();
System.out.println("i)(1) Insert an item to the Hash Table" +
"\nii)(2) Search A Specific Key" +
"\niii)(3) Display the Table" +
"\nvii)(4) Quit");
String input = scan.next();
switch(input){
case "1":
System.out.println();
System.out.println("Enter value to add to table");
String desKey1 = scan.next();
table.insert(desKey1);
continue;
case "2":
System.out.println("Please enter specific key desired:\t");
String desKey2 = scan.next();
if(table.searchKey(desKey2).equals(desKey2)){
System.out.println("Key Found");
System.out.println("Number of cells accessed:\t" + table.numOfEntries());
}
else{
System.out.println("Key Not Found");
}
continue;
case "3":
table.print();
continue;
case "4":
temp = 4;
break;
}
}
}
}

Sorted / Not sorted - How do I print the answer to the console?

I've got a program that checks whether a list is sorted or not. How do I print the answer? (i.e "The list is sorted", "The list is not sorted").
public class CheckList {
public static void main(String[] args) {
int[] myList = new int[10];
// Read in ten numbers
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers: ");
for (int i = 0; i < myList.length; i++) {
myList[i] = input.nextInt();
}
}
//Check if list is sorted
public static boolean isSorted(int[] myList) {
if (myList[0] > 1) {
for (int i = 1; i < myList[0]; i++)
if (myList[i] > myList[i + 1])
return false;
}
return true;
}
}
Just call the method inside a if:
if(isSorted(myList)) {
System.out.println("Array is sorted");
} else {
System.out.println("Array is not sorted");
}
Anyway, your isSorted method won't work, i would make something like this:
//checks if array is sorted in ascending order
public static boolean isSorted(int[] myList) {
if(myList == null) return false; //just checking
for (int i = 0; i < myList.length - 1; i++) {
if (myList[i] > myList[i + 1]) {
return false;
}
}
return true;
}
Just call the method after your for loop
for (int i = 0; i < myList.length; i++) {
myList[i] = input.nextInt();
}
if(isSorted(myList)) {
System.out.println("The list is sorted");
} else {
System.out.println("The list is not sorted");
}

Categories

Resources