I 'm looking for a way to read a range of elements in an array of unknown dimension ( not length).
The client can send a read request for an object and specify the range to read. The input String could be like this : "1:2:3:2,2:3:1:4" for example. This would mean he wants to read the elements in the range from [1][2][3][2] to [2][3][1][4] of an array.
To read a concrete element I created this function:
public Object readValue(Object obj,int[] positions ) {
Object value = null; //Result
int objDimension = getDimension(obj); //Dimesion of the array
System.out.println("Dimension: " + objDimension );
try {
Object[] aux = (Object[]) obj;
for (int i = 0; i < objDimension - 1; i++) {
int pos = positions[i];
aux = (Object[]) aux[pos];
}
value = aux[positions[objDimension - 1]];
System.out.println("Result: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: Send a fault to the client.
System.out.println("Error: "+e.getMessage());
}
return value;
}
public static int getDimension(Object value) {
Class<?> clazz = value.getClass();
String className = clazz.getName();
int dimension = 0;
for (int i = 0; i < className.length(); i++) {
if (className.charAt(i) != '[') {
dimension = i;
break;
}
}
return dimension;
}
//Example.
public static void main(String[] args) {
// TODO code application logic here
TestMultiDimensioNRead test = new TestMultiDimensioNRead();
Integer[][][][] testSubject = new Integer[5][2][4][];
testSubject[0][0][2] = new Integer[8];
testSubject[0][0][0] = new Integer[15];
testSubject[0][0][1] = new Integer[20];
testSubject[0][0][3] = new Integer[2];
testSubject[1][1][2] = new Integer[7];
testSubject[1][1][2][0] = 80;
test.readValue(testSubject,new int[]{1, 1, 2, 0});
}
I was thinking a good way may be to calculate the differens between each dimension length.
If anyone can come with a good idea, I would really appreciatee.
Thanks in advance.
EDIT 1: The code posted in this question does read the value of a given position in an array of unknown dimension. My problem is to read all the elements that are between to given points. This might not have been clear in the initial question.
You could use a recursive solution:
public class Test {
private class TestMultiDimensioNRead {
public Integer readValue(Object testSubject, int[] coordinates) {
return readValue(testSubject, coordinates, 0);
}
private Integer readValue(Object testSubject, int[] coordinates, int which) {
if (testSubject instanceof Object[]) {
Object[] subject = (Object[]) testSubject;
if (coordinates.length > which + 1) {
return readValue(subject[coordinates[which]], coordinates, which + 1);
} else {
return (Integer) subject[coordinates[which]];
}
} else {
// Throw some sort of exception?
return -1;
}
}
public Iterator<Integer> readValues(Object testSubject, int[] coordinates, int count) {
return readValues(testSubject, coordinates, count, 0);
}
private Iterator<Integer> readValues(Object testSubject, int[] coordinates, int count, int level) {
if (testSubject instanceof Object[]) {
Object[] subject = (Object[]) testSubject;
if (coordinates.length > level + 1) {
return readValues(subject[coordinates[level]], coordinates, count, level + 1);
} else {
return new Iterator<Integer>() {
int i = 0;
Integer[] intSubject = (Integer[]) subject;
#Override
public boolean hasNext() {
return i <= count;
}
#Override
public Integer next() {
return intSubject[coordinates[level] + (i++)];
}
};
}
} else {
// Throw some sort of exception?
return null;
}
}
}
public void test() {
TestMultiDimensioNRead test = new TestMultiDimensioNRead();
Integer[][][][] testSubject = new Integer[5][2][4][];
testSubject[0][0][2] = new Integer[8];
testSubject[0][0][0] = new Integer[15];
testSubject[0][0][1] = new Integer[20];
testSubject[0][0][3] = new Integer[2];
testSubject[1][1][2] = new Integer[7];
testSubject[1][1][2][0] = 80;
testSubject[1][1][2][1] = 79;
testSubject[1][1][2][2] = 78;
Iterator<Integer> them = test.readValues(testSubject, new int[]{1, 1, 2, 0}, 3);
for (Integer x = them.next(); them.hasNext(); x = them.next()) {
System.out.println(x);
}
System.out.println();
}
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
}
Prints 80 as expected.
There's probably more to do in terms of sanity checks but this seems to work.
Found the way to do it, maybe it's helpfull at somepoint for someone.
I didn't include any checks, this is more a test case to see that is works.
public class TestReadMultiDimensionArray {
private int[] startPosition; //Start position.
private int[] endPosition; //End position.
private boolean inRange = false; //If the current position is in range.
private List<Object> result; //List to store the values we find.
public TestReadMultiDimensionArray() {
result = new ArrayList<>();
}
public static void main(String[] args) {
TestReadMultiDimensionArray test = new TestReadMultiDimensionArray();
Integer[][][][] testSubject = new Integer[2][2][4][];
//(0,0,y,z)
testSubject[0][0][0] = new Integer[]{1}; //(0,0,0,0)
testSubject[0][0][1] = new Integer[]{2}; //(0,0,1,0)
testSubject[0][0][2] = new Integer[]{3}; //(0,0,2,0)
testSubject[0][0][3] = new Integer[]{4}; //(0,0,3,0)
//(0,1,y,z)
testSubject[0][1][0] = new Integer[]{5}; //(0,1,0,0)
testSubject[0][1][1] = new Integer[]{6}; //(0,1,1,0)
testSubject[0][1][2] = new Integer[]{7, 8, 9}; //(0,1,2,0) (0,1,2,1) (0,1,2,2)
testSubject[0][1][3] = new Integer[]{10}; //(0,1,3,0)
//(1,0,y,z)
testSubject[1][0][0] = new Integer[]{11, 12}; //(1,0,0,0)..
testSubject[1][0][1] = new Integer[]{13, 14, 15};
testSubject[1][0][2] = new Integer[]{16, 17, 18};
testSubject[1][0][3] = new Integer[]{19, 20, 21}; //..(1,0,3,2)
//(1,1,y,z)
testSubject[1][1][0] = new Integer[]{22, 23}; //(1,1,0,0)..
testSubject[1][1][1] = new Integer[]{24, 25, 26};
testSubject[1][1][2] = new Integer[]{27, 28, 29, 30, 31, 32, 33, 34};
testSubject[1][1][3] = new Integer[]{35, 36}; //..(1,1,3,1)
//Launch the test.
test.readValue(testSubject);
}
/**
*
* #param obj The Array from where we want to get the data.
*/
public void readValue(Object obj) {
//Where should it start.
startPosition = new int[]{0, 1, 0, 0};
//Where should it stop.
endPosition = new int[]{1, 1, 1, 2};
System.out.println("Start Position:" + Arrays.toString(startPosition) + " End Position:" + Arrays.toString(endPosition));
int[] currentPosition = new int[]{-1, -1, -1, -1};
//Call to the method.
testRead((Object[]) obj, 0, currentPosition);
//Result to array.
Object[] arrayToReturn = result.toArray(new Object[0]);
System.out.println("Result: " + Arrays.toString(arrayToReturn));
}
/**
* Recursive method that looks for the values in a multi-dimensional array, in a given range. /!\ No checks are implemented here, wrong input can end in a
* StackOverFlow.
*
* #param obj The array in Object[] form.
* #param currentDimension The dimension we are currently in.
* #param result The reference to the list that will store all the values we found.
* #param currentPosition The current position we are in.
*/
private void testRead(Object[] obj, int currentDimension, int[] currentPosition) {
for (int i = 0; i < obj.length; i++) {
currentPosition[currentDimension] = i;
if (Arrays.equals(startPosition, currentPosition) && currentDimension == (currentPosition.length - 1)) {
//Found the start position.
System.out.println("############ START ############");
inRange = true;
}
if ((i >= startPosition[currentDimension] && i <= endPosition[currentDimension]) || inRange == true) {
//We are in the write track to get to the values we are looking for.
if (obj[i] instanceof Object[]) {
//The data contained in the cell is an array.
testRead((Object[]) obj[i], currentDimension + 1, currentPosition);
} else {
//The data contained in the cell is a scalar. This is what we where looking for.
System.out.println(Arrays.toString(currentPosition) + " Data: " + obj[i]);
result.add(obj[i]);
}
}
if (Arrays.equals(endPosition, currentPosition) && currentDimension == (currentPosition.length - 1)) {
//Found the end position.
System.out.println("############ END ############");
inRange = false;
}
}
}
}
Any question or idea to better the code is welcome.
I have coded a simple memory game. Card values are added to two arrays and after that, a compare function is called. But there is a problem with the logic of the compare function.
The specific problem seems related to the fact that the compare function is called on the third button click. So on first click it adds first value to first array , on second click second value to second array. But I must click for yet a third time to call the compare function to compare the match of two arrays.
The main problem is that after all cards are inverted (10 matches in 5x4 memory game), it does not show the result.
I have uploaded full code here : http://uloz.to/xcsJkYUK/memory-game-rar .
public class PEXESO5x4 extends JFrame implements ActionListener {
private JButton[] aHracieTlactika = new JButton[20];
private ArrayList<Integer> aHodnoty = new ArrayList<Integer>();
private int aPocitadlo = 1;
private int[] aTlacitkoIden = new int[2];
private int[] aHodnotaTlac = new int[2];
private JButton aTlacitkoExit;
private JButton aTlacitkoReplay;
private JButton[] aHracieTlacitko = new JButton[20];
private int aPocetTahov = 0;
public void vkladanieHodnot() {
for (int i = 0; i < 2; i++) {
for (int j = 1; j < (this.aHracieTlactika.length / 2) + 1; j++) {
this.aHodnoty.add(j);
}
}
Collections.shuffle(this.aHodnoty);
}
public boolean zhoda() {
if (this.aHodnotaTlac[0] == this.aHodnotaTlac[1]) {
return true;
}
return false;
}
public void zapisCislaDoSuboru() {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Semestralka.txt", true)))) {
out.println("haha");
//more code
out.println("hahahahha");
//more code
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
public void actionPerformed(ActionEvent e) {
int match = 0;
if (this.aTlacitkoExit == e.getSource()) {
System.exit(0);
}
if (this.aTlacitkoReplay == e.getSource()) {
}
for (int i = 0; i < this.aHracieTlactika.length; i++) {
if (this.aHracieTlactika[i] == e.getSource()) {
this.aHracieTlactika[i].setText("" + this.aHodnoty.get(i));
this.aHracieTlactika[i].setEnabled(false);
this.aPocitadlo++;
this.aPocetTahov += 1;
if (this.aPocitadlo == 3) {
if (this.zhoda()) {
match+=1;
if (match==10)
{
System.out.println("You win");
}
this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(false);
this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(false);
} else {
this.aHracieTlactika[this.aTlacitkoIden[0]].setEnabled(true);
this.aHracieTlactika[this.aTlacitkoIden[0]].setText("");
this.aHracieTlactika[this.aTlacitkoIden[1]].setEnabled(true);
this.aHracieTlactika[this.aTlacitkoIden[1]].setText("");
}
this.aPocitadlo = 1;
}
if (this.aPocitadlo == 1) {
this.aTlacitkoIden[0] = i;
this.aHodnotaTlac[0] = this.aHodnoty.get(i);
}
if (this.aPocitadlo == 2) {
this.aTlacitkoIden[1] = i;
this.aHodnotaTlac[1] = this.aHodnoty.get(i);
}
}
}
}
}
I am trying to create a table based on my trial class. When I try to run my table class the table prints with the proper heading, but it does not print anything in the body of the table. How should I fix my for loop so the data enters the table? Do I need to add a parameter to the constructor?
I understand there are more getters and setters than necessary. I was just trying to go about the for loop in different ways.
public class Trial extends JFrame{
static int counter = 0;
int laps = 0;
String lapTime;
double currentTime = 0;
String difference;
int lapsCount = 0;
String[] array1;
double[] array2;
double[] array3;
public int getLapsCount() {
return lapsCount;
}
public void setLapsCount(int lapsCount) {
this.lapsCount = lapsCount;
}
public static int getCounter() {
return counter;
}
public static void setCounter(int counter) {
Trial.counter = counter;
}
public int getLaps() {
return laps;
}
public void setLaps(int laps) {
this.laps = laps;
}
public String getLapTime() {
return lapTime;
}
public void setLapTime(String lapTime) {
this.lapTime = lapTime;
}
public double getCurrentTime() {
return currentTime;
}
public void setCurrentTime(double currentTime) {
this.currentTime = currentTime;
}
public String getDifference() {
return difference;
}
public void setDifference(String difference) {
this.difference = difference;
}
public String[] getArray1() {
return array1;
}
public void setArray1(String[] array1) {
this.array1 = array1;
}
public double[] getArray2() {
return array2;
}
public void setArray2(double[] array2) {
this.array2 = array2;
}
public double[] getArray3() {
return array3;
}
public void setArray3(double[] array3) {
this.array3 = array3;
}
public static void main(String[] args) {
//drop down for number of laps
String lapsString;
String[] selections = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
lapsString = (String) JOptionPane.showInputDialog(null,
"Choose a number of laps:",
"Lap Counter",
JOptionPane.INFORMATION_MESSAGE,
null, /* icon */
selections,
"0");
System.out.printf("Number of laps = \"%s\"\n", lapsString);
int lapsCount = Integer.parseInt(lapsString);
String[] array1 = new String[lapsCount+1];
double[] array2 = new double[lapsCount+1];
double[] array3 = new double[lapsCount+1];
// showInputDialog with for lap time
for (int i = 1; i <= lapsCount; i++){
String lapTime;
lapTime =
JOptionPane.showInputDialog("Enter lap " + i + " total time.");
System.out.printf("Lap " + i + " = \"%s\"\n", lapTime);
array1[i] = lapTime;
double currentTime = inputConvert(array1[i]);
array2[i] = currentTime;
array3[i] = (array2[i] - array2[i-1]);
counter++;
//confirm each time
int result;
String[] results = { "Yes", "No", "Cancel" };
result = JOptionPane.showConfirmDialog(null,
"Please confirm lap " + i + " is " + lapTime);
if (result == -1)
System.out.printf("user closed window\n");
else if (result == 0)
System.out.printf("result = %d, user pressed \"%s\"\n", result, results[result]);
else {
lapTime =
JOptionPane.showInputDialog("Please re-enter lap " + i);
System.out.printf("Lap " + i + " = \"%s\"\n", lapTime);
counter++;
}
}
}
public static double inputConvert(String s) {
double convert = 0.0;
int minutes = Integer.parseInt(s.substring(0, 1));
double seconds = Double.parseDouble(s.substring(2, s.length()));
minutes = minutes * 60;
convert = minutes + seconds;
return convert;
}
private static String getDifference(int j, double sign) {
String difference = "";
if(j == 0) {
difference = "---";
}
else if(sign > 0.0) {
difference = "+";
}
return difference;
}
public static String displayTime(double time) {
String result = null;
int minutes = (int) (time/60);
double seconds = (time % 60);
seconds = Math.round(seconds*100.0)/100.0;
if(seconds < 10){
result = minutes + ":0" + seconds;
}
else{
result = minutes + ":" + seconds;
}
return result;
}
}
This is my table class where the problem arises.
public class table {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new table();
}
});
}
public table() {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Table to record lap times");
guiFrame.setSize(700,200);
guiFrame.setLocationRelativeTo(null);
JTable table = new JTable(new ExampleTableModel());
table.setAutoCreateRowSorter(true);
table.setGridColor(Color.YELLOW);
table.setBackground(Color.CYAN);
JScrollPane tableScrollPane = new JScrollPane(table);
guiFrame.add(tableScrollPane);
guiFrame.setVisible(true);
}
class ExampleTableModel extends AbstractTableModel{
int laps = 0;
String lapTime;
double currentTime = 0;
String difference;
Trial t = new Trial();
//Two arrays used for the table data
private String[] columnNames = {"Lap #", "Total Time", "Lap Time" , "Difference" };
private Object[][] data;
public ExampleTableModel(){
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = t.getArray1() [i];
data[i][2] = t.getArray2()[i];
data[i][3] = t.getArray3()[i];
}
}
#Override public int getRowCount() {
return data.length;
}
#Override public int getColumnCount() {
return columnNames.length;
}
#Override public Object getValueAt(int row, int column) {
return data[row][column];
}
#Override public String getColumnName(int column) {
return columnNames[column];
}
#Override public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override public boolean isCellEditable(int row, int column) {
if (column == 0 || column == 1) {
return false;
}
else {
return true;
}
}
}
}
I made those changes but I need my output to look like this
Lap #: Total time Lap time Difference
Lap1: 2:10 2:10 ---
I fixed the lap number so it starts at 1. I made these changes in the hopes that it would fix the lap time and difference cells but it is giving me an error.
public ExampleTableModel(Trial trial){
int laps = trial.getLapsCount();
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
if (i == 0){
data[i][0] = "Lap " + (i + 1);
data[i][1] = trial.getArray1() [i + 1];
data[i][2] = trial.getArray2() [i + 1];
data[i][3] = trial.getDifference(i, (trial.getArray3()[i + 1] - trial.getArray3()[i]));
}
else {
data[i][0] = "Lap " + (i + 1);
data[i][1] = trial.getArray1() [i + 1];
data[i][2] = trial.displayTime(trial.getArray2() [i + 1] - trial.getArray2() [i]);
data[i][3] = trial.getDifference(i, (trial.getArray3()[i + 1] - trial.getArray3()[i])) + (trial.getArray3()[i + 1] - trial.getArray3()[i]);
}
}
}
Edit: combining the code from the Trial.main and the Table.main methods
To make the code from your Trial class easier to use from the Table class, you can make the following changes. This way you can create a Trial object and call the getUserInput to let the user initialize it:
public static void main(String[] args) {
new Trial().getUserInput();
}
public void getUserInput() {
// [Code from the old main method...]
// Use the fields of the class instead of local variables:
lapsCount = Integer.parseInt(lapsString);
array1 = new String[lapsCount+1];
array2 = new double[lapsCount+1];
array3 = new double[lapsCount+1];
// [Code from the old main method...]
}
Now you can modify the Table model like this:
public Table() {
// [...]
Trial trial = new Trial();
trial.getUserInput();
JTable table = new JTable(new ExampleTableModel(trial));
// [...]
}
And let the ExampleTableModel constructor use a trail parameter (the laps and t fields are no longer used):
public ExampleTableModel(Trial trial){
int laps = trial.getLapsCount();
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = trial.getArray1()[i];
data[i][2] = trial.getArray2()[i];
data[i][3] = trial.getArray3()[i];
}
}
There was also an issue with the getColumnClass method:
#Override public Class getColumnClass(int column) {
//return getValueAt(0, column).getClass();
return (column <= 1) ? String.class : Double.class;
}
Now the table looks like this:
The output was:
Number of laps = "2"
Lap 1 = "2:10"
result = 0, user pressed "Yes"
Lap 2 = "2:20"
result = 0, user pressed "Yes"
Old answer
There seem to be a few issues that prevent the table from being filled:
In the ExampleTableModel class the laps field should be something higher than zero (for the constructor to fill the data array):
class ExampleTableModel extends AbstractTableModel {
//int laps = 0;
int laps = 6;
In the constructor of the ExampleTableModel class:
public ExampleTableModel(){
data = new Object[laps][4];
for(int i = 0; i < laps; i++){
data[i][0] = "Lap " + i;
data[i][1] = t.getArray1()[i];
data[i][2] = t.getArray2()[i];
data[i][3] = t.getArray3()[i];
}
}
the calls to the t.getArray1, t.getArray2, and t.getArray3 methods return null. The Trial object appears to have no data yet.
Do you want your program to execute both the code of the Trial.main method and the Table.main method?
I have an array that I want to sort in ascending order. However, I want to sort them with reference to a boolean array.I would like to sort the values that are true in ascending order, followed by the values that are false in ascending order.
Little stuck on how to get there.
This is what I have currently:
Object[] arr = new Object[6];
arr[0] = new Object(2);
arr[1] = new Object(5);
arr[2] = new Object(3);
arr[3] = new Object(1);
arr[4] = new Object(6);
arr[5] = new Object(4);
Available[] avalarr = new Available[6];
availarr[0] = new Available (true);
availarr[1] = new Available (false);
availarr[2] = new Available (false);
availarr[3] = new Available (true);
availarr[4] = new Available (true);
availarr[5] = new Available (false);
I need the output to be:
1 2 6 3 4 5
Code:
import java.util.Arrays;
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
Arrays.sort(items);
System.out.println("\n\nAfter Sorting:");
// Removed enhanced for loop
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
}
class Item implements Comparable<Item> {
private int _intValue;
private boolean _boolValue;
public Item(int intValue, boolean boolValue) {
_intValue = intValue;
_boolValue = boolValue;
}
public int getIntValue() { return _intValue; }
public boolean getBoolValue() { return _boolValue; }
#Override
public int compareTo(Item otherItem) {
// Using explicit comparison
int boolComparison = (_boolValue == otherItem._boolValue) ? 0 :
(_boolValue) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (_intValue == otherItem.getIntValue()) ? 0 :
(_intValue > otherItem.getIntValue()) ? 1 : -1);
}
}
Output:
Before Sorting:
2 5 3 1 6 4
After Sorting:
1 2 6 3 4 5
Explanation:
The idea is to let your "Item" implement Comparable, and override the compareTo(Item otherItem) function based on the desired order.
Once that is done, all you need to do is to call Arrays.sort() on your array of Item.
Version 2 (w/o Comparable/Comparator):
public class SelectiveSort {
public static void main(String[] args) {
Item [] items = new Item [6];
items[0] = new Item(2, true);
items[1] = new Item(5, false);
items[2] = new Item(3, false);
items[3] = new Item(1, true);
items[4] = new Item(6, true);
items[5] = new Item(4, false);
System.out.println("Before Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
// Sorting
bubbleSort(items);
System.out.println("\n\nAfter Sorting:");
for(int i = 0; i < items.length; i++) {
System.out.print(items[i].getIntValue() + " ");
}
System.out.println();
}
public static void bubbleSort(Item [] items) {
int n = items.length;
do {
int newN = 0;
for(int i = 1; i < n; i++) {
if(compareTo(items[i-1], items[i]) == 1) {
Item temp = items[i-1];
items[i-1] = items[i];
items[i] = temp;
newN = i;
}
}
n = newN;
} while (n != 0);
}
public static int compareTo(Item item1, Item item2) {
int boolComparison = (item1.getBoolValue() == item2.getBoolValue())
? 0 : (item1.getBoolValue()) ? 1 : -1;
return (boolComparison != 0) ? -boolComparison :
( (item1.getIntValue() == item2.getIntValue()) ? 0 :
(item1.getIntValue() > item2.getIntValue()) ? 1 : -1);
}
}
(To expand on my comment:
You need a basic "thing":
class Thing {
boolean newAvailable;
int order;
public Thing(boolean newAvailable, int order) {
...
}
}
...and a Comparable...
class CompareThings implements Comparator<Thing> {
...
int compare(Thing t1, Thing t2) {
if (t1.newAvailable!=t2.newAvailable)
return t1.newAvailable==true ? 1 : -1;
return t1.order-t2.order;
}
}
(Note that t1.newAvailable==true is redundant, but I think it clarifies what's going on here.)
Now build an array of Thing and call Arrays.sort(Thing[] things, CompareThings);
I'm currently trying to convert my code to ArrayList and I can't seem to make it work. I'm running the whole program and it tells me Index out bounds. I'm sure I forgot to add the size of the array for the cards, but I don't know how to add it. Thanks for the help!
Edit: The error I get is at the bottom. Also, it tells me to go to the removeTop method. It looks fine there.
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class CardPile {
private ArrayList<Card> cards = new ArrayList<Card>();
private static Random r = new Random(1);
public void addToBottom(Card c) {
if (this.cards.size() == 52) {
System.out.println("The CardPile is full. You cannot add any more Card objects.");
}
this.cards.add(c);
}
public Card removeCard(Card c) {
if (this.cards.contains(c)) {
this.cards.remove(c);
}
return null;
}
public Card removeTop() {
return this.cards.remove(0);
}
public int searchValue(int value) {
int count = 0,
for (int i = 0;i < this.cards.size();i++) {
if (this.cards.get(i).getValue() == value) {
count++;
}
}
//System.out.println("Count = "+count);
return count;
}
public Card[] removeAll(int value)
//System.out.println("(removeAll) cards ="+ cards);
int count = searchValue(value);
Card[] removed = new Card[count];
int deletedCount = 0;
int i = 0;
while (deletedCount < count) {
if (this.cards.get(i).getValue() == value) {
removed[deletedCount] = this.cards.remove(i);
deletedCount++;
} else {
i++;
}
}
return removed;
}
public int getNumberCards() {
return this.cards.size();
}
public String toString() {
if (this.cards.isEmpty()) {
return "";
}
String builder = "";
for (int i = 0;i < this.cards.size() - 1;i++) {
builder = builder + this.cards.get(i) + ", ";
}
builder = builder + this.cards.get(this.cards.size() - 1);
return builder;
}
public void shuffle() {
if (this.cards.isEmpty()) {
return;
}
for (int count = 0; count < 100000;count++) {
int i = r.nextInt(this.cards.size());
int j = r.nextInt(this.cards.size());
Card temp = this.cards.get(i);
this.cards.set(i, this.cards.get(j));
this.cards.set(j, temp);
}
}
public static CardPile makeFullDeck() {
CardPile deck = new CardPile();
for (int suit = 0;suit < 4;suit++) {
for (int value = 1; value <= 13;value++) {
deck.addToBottom(new Card(suit, value));
}
}
deck.shuffle();
return deck;
}
}
**Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at CardPile.removeTop(CardPile.java:40)
at GoFish.dealCards(GoFish.java:112)
at GoFish.main(GoFish.java:13)**
EDIT:
This is the Player class:
public class Player {
private boolean[] books;
private CardPile pile;
private static int MAXIMUM_VALUE_CARD = 13;
public Player()
{
this.pile = new CardPile();
this.books = new boolean[13]; //by default all are false
}
public boolean hasCard(int value)
{
return this.pile.searchValue(value) > 0;
}
public Card[] removeAll(int value)
{
return this.pile.removeAll(value);
}
public void addAll(Card[] cards)
{
for (int i = 0; i < cards.length; i++)
{
this.pile.addToBottom(cards[i]);
}
}
//optional additional method
public void addCard(Card card)
{
this.pile.addToBottom(card);
}
public int getNumberCards()
{
return this.pile.getNumberCards();
}
public int countBooks()
{
int count = 0;
for (int i = 0; i < MAXIMUM_VALUE_CARD; i++)
{
if (books[i])
{
count++;
}
}
return count;
}
public void addBook(int value)
{
this.books[value - 1] = true;
}
public void printHand()
{
System.out.println("Player's hand is " + this.pile);
}
}
And this is the GoFish class:
import java.util.Scanner;
public class GoFish {
private static Scanner reader;
public static void main(String[] args)
{
System.out.println("How many players?");
reader = new Scanner(System.in);
int numberPlayers = reader.nextInt();
Player[] players = createPlayersArray(numberPlayers);
int currentTurn = 0;
CardPile deck = CardPile.makeFullDeck();
dealCards(deck, players);
int maximumRetries = 2;
int numRetries = 0;
while(deck.getNumberCards() > 0 && players[currentTurn].getNumberCards() > 0)
{
updateBooks(players[currentTurn]);
if (numRetries == maximumRetries)
{
numRetries = 0;
currentTurn++;
if (currentTurn == numberPlayers)
{
currentTurn = 0;
}
}
System.out.println("Player " + currentTurn + ", here is your hand. What card would you like to ask for?");
players[currentTurn].printHand();
int queryCard = reader.nextInt();
System.out.println("And from whom would you like to get it from?");
int queryPlayer = reader.nextInt();
if (queryCard < 1 || queryCard > 13 || queryPlayer < 0 || queryPlayer >= numberPlayers || queryPlayer == currentTurn)
{
System.out.println("Invalid entries. Please retry");
numRetries++;
}
else
{
numRetries = 0;
boolean hasCard = players[queryPlayer].hasCard(queryCard);
if (hasCard)
{
System.out.println("Cards found!");
Card[] removed = players[queryPlayer].removeAll(queryCard);
players[currentTurn].addAll(removed);
}
else
{
System.out.println("Go fish!");
Card top = deck.removeTop();
System.out.println("You drew " + top);
players[currentTurn].addCard(top);
//check to make sure this extra card didn't form a book
//Note this could happen even if it doesn't match the card they were asking about
updateBooks(players[currentTurn]);
if (top.getValue() == queryCard)
{
System.out.println("You successfully went fishing!");
}
else
{
currentTurn++;
if (currentTurn == numberPlayers)
{
currentTurn = 0;
}
}
}
}
}
//calculate the winner now
int maxPlayer = 0;
int maxPlayerBooks = players[0].countBooks();
for (int i = 1; i < numberPlayers; i++)
{
int currentBooks = players[i].countBooks();
if (currentBooks > maxPlayerBooks)
{
maxPlayer = i;
maxPlayerBooks = currentBooks;
}
}
System.out.println("Congratulations! Player " + maxPlayer + " you have won the game by accumulating " + maxPlayerBooks + " books!");
}
private static Player[] createPlayersArray(int numPlayers)
{
Player[] players = new Player[numPlayers];
for (int i = 0; i < numPlayers; i++)
{
players[i] = new Player();
}
return players;
}
private static void dealCards(CardPile deck, Player[] players)
{
final int NUMBER_CARDS_PER_PLAYER = 7;
for (int i = 0; i < NUMBER_CARDS_PER_PLAYER * players.length; i++)
{
Card next = deck.removeTop();
players[i % players.length].addCard(next);
}
}
private static void updateBooks(Player player)
{
for (int i = 1; i <= 13; i++)
{
//alternative option would be to modify the hasCard method to return an int instead of boolean. Then we could just count (this is probably better design)
Card[] valued = player.removeAll(i);
if (valued.length == 4)
{
player.addBook(i);
}
else
{
player.addAll(valued);
}
}
}
}