Question

This is for a java lab, in class instruction we are not allowed to use "this". if anyone can help, and explain the importance of "this" and as to why we should or should not use it. Thank you in advanced.

A: Create a class called Tile. * An object of this class represents a tile in the game called Qwirkle. You can look up the description and game play instructions online A Qwirkle tile has two attributes: 1. · color-implement this as an integer between 1 and 6 (inclusive). The colors are orange, green, yello, red, blue, and purple. 2. shape- implement this as an integer between 1 and 6 (inclusive). The shapes are four-pointed star, clover, eight-pointed star, diamond, square, and circle A Qwirkle tile has typical object-oriented behaviors (only these) 1. create a tile with a given color and given shape 2. access the color of the tile 3. access the shape of the tile 4. change the color of the tile S. change the shape of the tile 6. provide a String representation of the tile 7. compare one tile for equality with another 8. clone a tile Reminder: Incremental Programming Write a little bit of code. Compile, debug. Repeat. B: Create a test program for the QwirkleBag class (.. .coming up in part C). Name your program QwirkleTester java. e Write a main method . Inside the main method, start with the statements QwirkleBag game1-new QwirkleBag) ystem.out.printin( I created a new QwirkleBag. Heres whats in it:n) System.out.printin (game1)i * Now go to part C and do the steps at least up to the toString method. Then come back, compile, and run the test program.

Intarraybag.java:


public class IntArrayBag implements Cloneable
{

// instance variables

private int[ ] data;
private int manyItems;

// constructor : behavior #1

public IntArrayBag( )
{
final int INITIAL_CAPACITY = 10;

manyItems = 0;

data = new int[INITIAL_CAPACITY];
}

// another constructor : behavior #1

public IntArrayBag(int initialCapacity)
{
if (initialCapacity < 0)

throw new IllegalArgumentException
("The initialCapacity is negative: " + initialCapacity);


data = new int[initialCapacity];
manyItems = 0;
}
  

// add one item : behavior #2

public void add(int element)
{
if (manyItems == data.length)
{ // Ensure twice as much space as we need.
ensureCapacity((manyItems + 1)*2);
}

data[manyItems] = element;
manyItems++;
}

// add many items : behavior #3

public void addMany(int... elements)

// this is a variable arity method. We can specify as many parameters
// as needed

{
if (manyItems + elements.length
> data.length)
{ // Ensure twice as much space as we need.
ensureCapacity((manyItems + elements.length)*2);
}

System.arraycopy(elements, 0, data, manyItems, elements.length);
manyItems += elements.length;
}


public void addAll(IntArrayBag addend)
{
ensureCapacity(manyItems + addend.manyItems);

System.arraycopy(addend.data, 0, data, manyItems, addend.manyItems);
manyItems += addend.manyItems;
}

public IntArrayBag clone( )
{ // Clone an IntArrayBag object.
IntArrayBag answer;
  
try
{
answer = (IntArrayBag) super.clone( );
}
catch (CloneNotSupportedException e) {
throw new RuntimeException
("This class does not implement Cloneable");
}  
answer.data = data.clone( );
  
return answer;
}

// see the remainder of the IntArrayBag.java file in
// the Sept 7 notes

public int countOccurrences(int target)
{
int count = 0;
  
for (int index = 0; index < manyItems; index++)
if (target == data[index])
count++;

return count;
}
public void ensureCapacity(int minimumCapacity)
{
int biggerArray[ ]; // declaration
  
if (data.length < minimumCapacity)
{
biggerArray = new int[minimumCapacity]; // allocate space

System.arraycopy(data, 0, biggerArray, 0, manyItems);

data = biggerArray;  
}
}

  

public int getCapacity( )
{
return data.length;
}

  
public boolean remove(int target)
{
int index; // must declare before the loop

for (index = 0; (index < manyItems) && (target != data[index]);
index++)
;

if (index == manyItems) // target was not found
return false;
else
{  
manyItems--;
data[index] = data[manyItems];
return true;
}
}

public int size( )
{
return manyItems;
}


public void trimToSize( )
{
int trimmedArray[ ];
  
if (data.length != manyItems)
{
trimmedArray = new int[manyItems];
System.arraycopy(data, 0, trimmedArray, 0, manyItems);
data = trimmedArray;
}
}
  

public static IntArrayBag union(IntArrayBag b1, IntArrayBag b2)
{

// a call to this method would look like
// IntArrayBag.union( first IntArrayBag, second IntArrayBag )


// If either b1 or b2 is null, then a NullPointerException is
// thrown.
// In the case that the total number of items is beyond
// Integer.MAX_VALUE, there will be an arithmetic overflow and
// the bag will fail.

IntArrayBag answer = new IntArrayBag(b1.getCapacity( ) +   
b2.getCapacity( ));
  

// Dr. Steiner replaced the calls to System.arraycopy
// with two simple loops

for (int i = 0; i < b1.manyItems; i++)
answer.data[i] = b1.data[i];

for (int j = 0; j < b2.manyItems; j++)
answer.data[b1.manyItems + j] = b2.data[j];


answer.manyItems = b1.manyItems + b2.manyItems;
  
return answer;
}
  
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

"this" keyword works as a reference to the current object of the class. It is like a reminder to other programmers of the scope of variables. There are some arguments for and against the use of "this".Majorly it is to flag/tag the scope of any variable in a class.

One place where "this" is commonly used is constructors and setters. If you have started using "this" in your program make sure that this convention is strictly followed as it will be considered a local variable by other programmers if not marked "this".

it is necessary in some cases like:

class Test{
  int field1;

  public Test(int field1) {
    this.field1=field1;
  }
}

So if there are any common names among local variables(of any method of a class) and class variables, then only I would prefer use of this.

Add a comment
Know the answer?
Add Answer to:
This is for a java lab, in class instruction we are not allowed to use "this"....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY....

    PLEASE EDIT THE LAST 3 METHODS WHERE I PUT STARS AND DO WHAT THE COMMENTS SAY. THE CODE IS IN JAVA PROGRAMMING LANGUAGE. import java.util.AbstractList; import java.util.List; import java.util.RandomAccess; import java.lang.RuntimeException; import java.util.Arrays; public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess {    protected Object[] data; protected int size; public int size() {     return size; }    private void rangeCheck(int index) {     if (index < 0 || index >= size) throw new IndexOutOfBoundsException(""); }    @SuppressWarnings("unchecked") private E...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private...

  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

  • JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final...

    JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final int DEFAULT_CAPACITY = 2;   //default initial capacity / minimum capacity    private T[] data;   //underlying array    // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!       @SuppressWarnings("unchecked")    public SmartArray(){        //constructor        //initial capacity of the array should be DEFAULT_CAPACITY    }    @SuppressWarnings("unchecked")    public SmartArray(int initialCapacity){        // constructor        // set the initial capacity of...

  • Write a class named Octagon (Octagon.java) that extends the following abstract GeometricObject class and implements the...

    Write a class named Octagon (Octagon.java) that extends the following abstract GeometricObject class and implements the Comparable and Cloneable interfaces. //GeometricObject.java: The abstract GeometricObject class public abstract class GeometricObject { private String color = "white"; private boolean filled; private java.util.Date dateCreated; /** Construct a default geometric object */ protected GeometricObject() { dateCreated = new java.util.Date(); } /** Construct a geometric object with color and filled value */ protected GeometricObject(String color, boolean filled) { dateCreated = new java.util.Date(); this.color = color;...

  • Rewrite the Course class in Listing 10.6 to implement the comparable and the cloneable interfaces. The...

    Rewrite the Course class in Listing 10.6 to implement the comparable and the cloneable interfaces. The clone method must allow a deep copy on the students field. In addition, add the equals(Object o) and the toString() methods. Write a test program to invoke the compareTo, clone, equals, and toString methods in a meaningful way. Below is the Listing from the book that needs to be rewritten public class Course {    private String courseName;    private String[] students = new...

  • package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic *...

    package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic * collection to store elements where indexes represent priorities and the * priorities can change in several ways. * * This collection class uses an Object[] data structure to store elements. * * @param <E> The type of all elements stored in this collection */ // You will have an error until you have have all methods // specified in interface PriorityList included inside this...

  • JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array...

    JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array storing elements in the list • topOfStack: an int value representing the location of the stack top in the array • INITIAL_CAPACITY: the default capacity of the stack public class ArrayBasedStack <E> { private E[] data; private int topOfStack; private static final int INITIAL_CAPACITY = 5; } Add a constructor that will initialize the stack with a user-defined initial capacity. The top of the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT