Java counter not counting properly - java
Hi I'm very new to Java and have this HW problem, we are asked to build Class LTile, a tile in the game of Scrabble.
The ID number of a tile should be assigned by a class/static data member, which keeps track of the number of LTile objects produced.
My ID output didn't not print from 1 to 26, instead, they are all assign 26.
I suspect my ID attribute must be wrong, but couldn't figure out the exactly error. Any help is greatly appreciated! Thanks!
package hw2;
public class LTile {
char letter;
private int value;
private static int ID=0;
public LTile(){
this.letter = '?';
this.value = 0;
LTile.ID++;
}
public LTile(char letter, int value){
this.letter=letter;
this.value=value;
LTile.ID++;
}
public char getLetter(){
return this.letter;
}
public int getValue(){
return this.value;
}
public int getID(){
return LTile.ID;
}
public boolean equals(Object obj){
if(this ==obj){
return true;}
else{
return false;
}
}
public String toString(){
return "["+ID+":" + letter+","+value+"]";
}
//**
//** main() for testing LTile
//**
public static void main(String[] args)
{
final String letters = "EAIONRTLSUDGBCMPFHVWYKJXQZ";
final int[] values = {1,1,1,1,1,1,1,1,1,1,2,2,3,3,3,3,4,4,4,4,4,5,8,8,10,10};
java.util.List<LTile> lst = new java.util.ArrayList<LTile>();
for (int i = 0; i < letters.length(); ++i)
lst.add(new LTile(letters.charAt(i), values[i]));
for (LTile tile : lst)
System.out.println(tile);
System.out.println();
// test for equals
boolean found = false;
for (int i = 0; i < lst.size()-1; ++i) {
for (int j = i+1; j < lst.size(); ++j) {
if (lst.get(i).equals(lst.get(j))) {
System.out.println("ERROR in equals() found for "
+ lst.get(i) + " and " + lst.get(j));
found = true;
}
}
}
if (!found)
System.out.println("No error in equals().");
}
}
My output is:
[26:E,1]
[26:A,1]
[26:I,1]
[26:O,1]
[26:N,1]
[26:R,1]
[26:T,1]
[26:L,1]
[26:S,1]
[26:U,1]
[26:D,2]
[26:G,2]
[26:B,3]
[26:C,3]
[26:M,3]
[26:P,3]
[26:F,4]
[26:H,4]
[26:V,4]
[26:W,4]
[26:Y,4]
[26:K,5]
[26:J,8]
[26:X,8]
[26:Q,10]
[26:Z,10]
No error in equals()
**The correct output should be:**
[1: E,1]
[2: A,1]
[3: I,1]
[4: O,1]
[5: N,1]
[6: R,1]
[7: T,1]
[8: L,1]
[9: S,1]
[10: U,1]
[11: D,2]
[12: G,2]
[13: B,3]
[14: C,3]
[15: M,3]
[16: P,3]
[17: F,4]
[18: H,4]
[19: V,4]
[20: W,4]
[21: Y,4]
[22: K,5]
[23: J,8]
[24: X,8]
[25: Q,10]
[26: Z,10]
No error in equals().
The ID number of a tile should be assigned by a class/static data member, which keeps track of the number of LTile objects produced.
This means that the id value should come from a static data member, not that it should be a static data member. So you need two fields: an instance id field to keep the object's id and a static CURRENT_ID field to keep track of how many objects you have created so far.
public class LTile {
char letter;
private int value;
private int id; // instance id
private static int CURRENT_ID = 0; // static counter from where the instance ids will be drawn
public LTile() {
// Call the other constructor to avoid unnecessary repetition
this('?', 0);
}
public LTile(char letter, int value) {
this.letter = letter;
this.value = value;
this.id = LTile.CURRENT_ID++;
}
// rest of the code
public int getID() {
return this.id;
}
public String toString() {
return "["+this.id+":" + this.letter+","+this.value+"]";
}
}
Note you also need to change getId() and toString() to use the instance id instead of the static counter.
Related
Generate a random integer on an interval
So I have this class called Organism: public class Organism implements Comparable{ // Represents the organisms guess for the unknown string String value; // String the organism is trying to guess String goalString; int n; public Organism(String goalString) { this.goalString = goalString; this.value = goalString; } public Organism(String value, String goalString, int n) { this.goalString = goalString; this.value = value; this.n = n; } public int fitness(){ // Represents the fitness of the organism int count = 0; for(int i = 0; i < goalString.length(); i++) { if(value.charAt(i) == goalString.charAt(i)) { count ++; } } return count; } public Organism[] mate(Organism other) { // Generate a random integer from [0, n-1] int crossOver; return new Organism[0]; } #Override public int compareTo(Object o) { return 0; } public void mutate(double mutateProb) { } #Override public String toString() { return "Value: " + value + " " + "Goal: " + goalString + " " + "Fitness: " + fitness(); } public String getValue() { return value; } public String getGoalString() { return goalString; } public int getN() { return n; } } Inside of the mate method I need to generate a random integer on the interval [0, n-1] where n is the length of value and goalString. I then need to store that inside of the crossOver variable inside of the mate method. What would be the best way to do that?
This should do the thing: int n = other.getValue().length() + other.getGoalString().length(); Random rand = new Random(); int crossOver = rand.nextInt(n); If you meant n should be the sum of the value and goalStrng of the current (this) object, simply remove the other. or replace it with this.. All have to be placed in the public Organism[] mate(Organism other) method.
Generic Linear List based on Arrays
I'm trying to write a Linear List based on arrays, but make the list be able to store any value by using Java Generics. This way I can create other programs that utilize it, but pass in different data types. I'm not entirely sure how to do this, any help would be appreciated. I guess Im struggling trying to set it up and create the functions. The generic type really messes me up. For example, trying to add a removeFirst() function, I cant use a loop like this: for (int i = 0; i < n - 1; i++) newList[i] = newList[i + 1]; — as it says The type of the expression must be an array type but it resolved to ArrayList. Fair warning, I'm still learning data structures. This is what I have so far: import java.util.ArrayList; public class LinearList<T> { private static int SIZE = 10; private int n = 0; private final ArrayList<T> newList = new ArrayList<T>(SIZE); private T t; public void set(T t) { this.t = t; } public T get() { return t; } public void add(T value, int position) { newList.add(position, value); n++; } public void addFirst(T value) { newList.add(0, value); n++; } public void removeLast() { T value = null; for (int i = 0; i < newList.size(); i++) value = newList.get(i); newList.remove(value); n--; } public void removeFirst() { newList.remove(0); n--; } public T first() { return newList.get(0); } public T last() { int value = 0; for (int i = 0; i < newList.size() - 1; i++) value++; return newList.get(value); } public int count() { return n; } public boolean isFull() { return (n >= SIZE); } public boolean isEmpty() { return (n <= 0); } //part 4 public void Grow() { int grow = SIZE / 2; SIZE = SIZE + grow; } public void Shrink() { int grow = SIZE / 2; SIZE = SIZE - grow; } public String toString() { String outStr = "" + newList; return outStr; } }
A good start would be to make it non-generic with a class you are comfortable with, such as an Integer. Once you have it set up, you can then make it generic by adding <T> to the class name, then replacing all references of Integer with T. public class MyArray{ becomes public class MyArray<T>{ public Integer add(Integer value){ becomes public T add(T value){ See What are Generics in Java? for more help
java incompatible types class data types
Hi this is my first post on here and I have hit a stump. I'm suppose to make a class based off a pre made data type class called Account. My main issues lie within public int findAccountByAcctNumber(int acctNumber) and public Account removeAccount(int index). The difficulty is how to create these methods with the different data types? import java.util.*; public class Bank { private ArrayList<Account> Accounts; private int currentSize; private String bankName; public Bank(String name) { bankName = name; Accounts = new ArrayList<Account>(0); } public void addAccount(Account acct){ Accounts.add(acct); } public int findAccountByAcctNumber(int acctNumber){ int tempIndex = -1; for(int i = 0; i < Accounts.size(); i++){ if(Accounts.get(i) == acctNumber){ tempIndex = i; } } return tempIndex; } public Account removeAccount(int index){ Accounts.remove(index); Account return index; } public String toString(){ String output = ""; output += bankName + "/n"; for(int i = 0; i < arrlist.size(); i++){ output += Accounts.get(i); } return output; } }
You haven't shown us the Account class, but I'm guessing it has a field accountNumber. You need to compare the input account number to the field, not the Account object itself: public int findAccountByAcctNumber(int acctNumber){ int tempIndex = -1; for(int i = 0; i < Accounts.size(); i++){ //NOT if(Accounts.get(i) == acctNumber){ -> if(Accounts.get(i).getAccountNumber() == acctNumber){ tempIndex = i; } } return tempIndex; } remove is pretty simple (ArrayList has already implemented this function): public Account removeAccount(int index){ return Accounts.remove(index); }
Set Implementation Equals Method Always returns false
One of my methods is not working in my Java implementation of the Set class. Why does equals always return false? public boolean equals(Set<E> s) { if(this.size() == s.size()){ for(int i = 0; i < size(); i++){ if(theData[i] == s.get(i)){ return true; } } } return false; } My set is Set<Integer> and I've compared a set of (1,2,3,4) and (1,2,3,4) together and it outputs false. EDIT: All of my sets are ordered from least to greatest. EDIT2: Here is my code dealing with equals in the main driver else if(spaceSplit[0].equals("equal")){ if(spaceSplit.length == 3){ String fSet = spaceSplit[1]; String sSet = spaceSplit[2]; int fSetIndex = 0; int sSetIndex = 0; for(int i = 0; i < sets.size(); i++){ if(((Set<Integer>) sets.get(i)).getName().equals(fSet)){ fSetIndex = i; } } for(int i = 0; i < sets.size(); i++){ if(((Set<Integer>) sets.get(i)).getName().equals(sSet)){ sSetIndex = i; } } System.out.println(sets.get(fSetIndex).equals(sets.get(sSetIndex))); } else { System.out.println("Parameters entered wrong, please try again."); } EDIT3: In my program I've been messing with it, and it outputs false everytime I put a real set in. If I just made up 2 sets that don't exist and call the equals method, it outputs true. I'm so confused. EDIT4: Here's more of the set code: import java.util.*; public class Set<E extends Comparable> { private String name; private int size = 0; private E[] theData; private static final int INITIAL_CAPACITY = 100; private int capacity = 0; public Set() { capacity = INITIAL_CAPACITY; theData = (E[]) new Integer[capacity]; } public Set(String name) { this.name = name; capacity = INITIAL_CAPACITY; theData = (E[]) new Integer[capacity]; } public String getName() { return name; } public void setName(String name) { this.name = name; } private void reallocate() { capacity = 2 * capacity; }
Your problem is you aren't overriding equals() The signature is not public boolean equals(Set<E>) It is public boolean equals(Object) That is why when you add the #Override annotation you get a compiler error. You must use Object as the parameter, then check for instanceof and cast.
The compare should be .equals instead of ==.
try like this: public boolean equals(Set<E> s) { if(this.size() == s.size()){ for(int i = 0; i < size(); i++){ if(!this.get(i).equals(s.get(i))){ return false; } } return true; } return false; }
implementing a method from one class to another?
I am making a program for airplane seating arrangements for a class and i ended up making two toString methods but when I run the program the toString method in my airplane class is making something not work specifically: str= str + seats[i][j].toString(); I believe that simply deleting the toString method in the seat class and somehow putting it back into the airplane class toString method would fix the problem or make it simpler. What's wrong? Airplane class: public class Airplane { private Seat [ ] [ ] seats; public static final int FIRST_CLASS = 1; public static final int ECONOMY = 2; private static final int FC_ROWS = 5; private static final int FC_COLS = 4; private static final int ECONOMY_ROWS = 5; private static final int ECONOMY_COLS = 6; public Airplane() { seats = new Seat[FC_ROWS][ECONOMY_COLS]; } public String toString() { String str = ""; for (int i=0; i<FC_ROWS; i++) { for (int j=0; j<ECONOMY_COLS; j++) { str= str + seats[i][j].toString(); } str = str + "\n"; } return str; } } Seat Class: public class Seat { private int seatType; private boolean isReserved; public static final int WINDOW = 1; public static final int AISLE = 2; public static final int CENTER = 3; public Seat(int inSeatType) { seatType = inSeatType; isReserved = false; } public int getSeatType() { return seatType; } public void reserveSeat() { isReserved = true; } public boolean isAvailable() { if (!isReserved) { return true; } else return false; } public String toString() { if(isReserved == false) { return "*"; } else return ""; } }
In Seat.toString you should print a " " not "". You're array is FC_ROWS by ECONOMY_COLS, so you're not creating all the seats. You should probably have two arrays (one for FC, one for Economy), since FC_ROWS != ECONOMY_ROWS. You aren't actually creating Seats in your constructor. Use a nested loop to create them, otherwise you will get a NullPointerException. Creating an array doesn't create the objects contained in the array. When you're creating the seats in the Airplane constructor, use if statements to figure out if the seat is supposed to be a Window, Aisle, etc.
seats seems to does not have Seat's instance. Add this code : for (int i=0; i<FC_ROWS; i++) { for (int j=0; j<ECONOMY_COLS; j++) { seats[i][j] = new Seat(); } } below this : seats = new Seat[FC_ROWS][ECONOMY_COLS];
I think that in Seat::toString, you mean to return " " (a space) if it isn't reserved.