sudoku game constructor - java

I am having trouble initializing a parameterless constructor with a defined game. Somehow it keeps on returning null if I use a getter method to return the game. Can anyone tell me what would be the best method to initialize the game?
Currently I'm calling a method from within another class which has a static method but it doesn't seem to work because it gives a null value if I get the game.
This is how I this game to be:
{{7,8,1,0,0,4,0,0,6},
{2,0,9,3,6,0,1,0,0},
{6,0,0,0,9,0,8,0,0},
{0,0,0,0,3,5,0,0,0},
{3,5,0,0,0,0,0,1,9},
{0,0,0,4,2,0,0,0,0},
{0,0,3,0,1,0,0,0,8},
{0,0,7,0,8,3,4,0,1},
{9,0,0,6,0,0,5,7,3}},
public class SudokuPlayer
{
private int [][] game;
public enum CellState { EMPTY, FIXED, PLAYED };
private CellState[][] gamestate;
private static final int GRID_SIZE=9;
public SudokuPlayer()
{
int[][] copy= SudokuGames.getGame(4);
int size = copy.length;
int[][] game = new int[GRID_SIZE][GRID_SIZE];
for ( int row = 0; row < size; row++)
{
for ( int col =0; col < size; col++)
{
game[row][col] = copy[row][col];
}
}
}
public int[][] getGame()
{
return game;
}
}
here is the method from a diferent class im calling:
public class SudokuGames {
public static final int [][][] GAMES = {
// Game 0 VE - DEFAULT 30 squares filled
{{5,3,0,0,7,0,0,0,0},
{6,0,0,1,9,5,0,0,0},
{0,9,8,0,0,0,0,6,0},
{8,0,0,0,6,0,0,0,3},
{4,0,0,8,0,3,0,0,1},
{7,0,0,0,2,0,0,0,6},
{0,6,0,0,0,0,2,8,0},
{0,0,0,4,1,9,0,0,5},
{0,0,0,0,8,0,0,7,9}},
// Game 1 VE
{{8,0,1,0,3,7,0,5,6},
{0,0,0,9,0,0,0,0,7},
{6,0,3,0,1,2,0,9,0},
{0,2,0,0,0,0,7,0,3},
{3,0,0,0,2,0,0,0,9},
{1,0,9,0,0,0,0,8,0},
{0,3,0,2,7,0,4,0,1},
{7,0,0,0,0,6,0,0,0},
{5,6,0,1,9,0,3,0,8}},
// Game 2 VE
{{0,9,0,0,3,0,1,4,0},
{7,0,3,0,0,4,0,0,8},
{5,0,0,6,0,7,0,2,0},
{0,7,4,5,0,2,9,0,0},
{1,0,0,0,0,0,0,0,2},
{0,0,9,1,0,8,4,6,0},
{0,5,0,7,0,9,0,0,6},
{4,0,0,2,0,0,5,0,1},
{0,8,6,0,5,0,0,7,0}},
// Game 3 VE
{{0,0,9,7,3,0,5,2,6},
{0,0,5,0,2,0,8,0,0},
{6,0,8,0,0,0,0,4,7},
{0,0,0,0,0,9,0,6,2},
{0,4,0,6,0,3,0,8,0},
{8,9,0,5,0,0,0,0,0},
{2,6,0,0,0,0,1,0,8},
{0,0,7,0,1,0,6,0,0},
{9,5,1,0,6,4,2,0,0}},
// Game 4 VE
{{7,8,1,0,0,4,0,0,6},
{2,0,9,3,6,0,1,0,0},
{6,0,0,0,9,0,8,0,0},
{0,0,0,0,3,5,0,0,0},
{3,5,0,0,0,0,0,1,9},
{0,0,0,4,2,0,0,0,0},
{0,0,3,0,1,0,0,0,8},
{0,0,7,0,8,3,4,0,1},
{9,0,0,6,0,0,5,7,3}},
// Game 5 E
{{0,0,0,9,1,0,0,0,2},
{5,0,0,0,0,0,0,0,0},
{3,0,0,5,4,0,0,6,8},
{0,4,2,7,0,0,3,0,5},
{0,0,3,4,5,6,2,0,0},
{1,0,9,0,0,8,7,4,0},
{8,1,0,0,7,5,0,0,4},
{0,0,0,0,0,0,0,0,1},
{9,0,0,0,8,4,0,0,0}},
// Game 6 E
{{0,0,0,1,0,7,0,9,0},
{0,0,0,4,9,0,3,0,0},
{6,0,0,0,3,0,4,1,0},
{4,0,5,0,0,0,0,3,0},
{8,2,0,0,0,0,0,5,4},
{0,3,0,0,0,0,2,0,6},
{0,1,4,0,7,0,0,0,5},
{0,0,8,0,2,5,0,0,0},
{0,6,0,8,0,1,0,0,0}},
// Game 7 E
{{0,0,2,8,0,7,5,0,0},
{6,0,0,0,0,0,0,0,4},
{0,8,0,0,6,0,0,7,0},
{1,3,0,4,0,9,0,2,5},
{0,0,0,0,0,0,0,0,0},
{4,5,0,7,0,1,0,6,8},
{0,6,0,0,3,0,0,9,0},
{5,0,0,0,0,0,0,0,7},
{0,0,1,6,0,4,2,0,0}}
}; //End
/**
* getGame(int gameID) returns a a Sudoku game as int [][]
* as specified by the gameID. If the gameID is outside the
* list of possible games, null is returned.
* #param gameID number of game to be played
* #return int[][] a game to be played
*/
public static int [][] getGame (int gameID) {
/** A little dangerous. A copy of the reference to the original array
* is returned. Not a copy of the array.
**/
if (gameID >= 0 && gameID < GAMES.length) {
return GAMES[gameID];
}
else {
return null;
}
}
}

You are hiding the instance variable.
Change the following
int[][] game = new int[GRID_SIZE][GRID_SIZE];
to
game = new int[GRID_SIZE][GRID_SIZE];

Related

Array will not update but rather print out the wrong array

I managed to figure out how to print the array for my connect four program but I cannot get the board to update with my code, I looked at it and ran it the code works in theory but however the array won't take the new inputs
Ive tried running it through with a for loop but that turned out wrong and I was thinking about putting the drop method in the print board method but I feel that that would result in an error
public class Connect4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// DON'T MODIFY THE MAIN METHOD UNLESS FOR DEBUGGING
//MAKE SURE YOU GET RID OF YOUR MODIFICATIONS HERE BEFORE
SUBMISSION
String[][] board = createEmptyBoard();
Scanner input = new Scanner(System.in);
boolean bl = true;
printPattern(board);
while(bl) {
int player1 = 1 , player2 = 2 , userInput;
System.out.println("Please drop a RED disk at the column between 0
and 6:");
userInput = input.nextInt();
dropDisk(board, userInput , player1);
printPattern(board);
System.out.println("Please drop a YELLOW disk at the column
between 0 and 6:");
userInput = input.nextInt();
dropDisk(board, userInput , player2);
printPattern(board);
String win = checkWinner(board);
/*
Write code to announce if there is winner and end the game
*/
}
}
public static String[][] createEmptyBoard() {
/* This method prints the first empty pattern for the game
DON'T MODIFY THIS METHOD
*/
String[][] f = new String[7][15];
for (int i =0;i<f.length;i++) {
for (int j =0;j<f[i].length;j++) {
if (j% 2 == 0) f[i][j] ="|";
else f[i][j] = " ";
if (i==6) f[i][j]= "-";
}
}
return f;
} // end of createEmptyBoard
public static void printPattern(String[][] brd) {
for (int i = 0; i < 7; i++){
System.out.println(brd[i][0] + brd[i][1]+ brd[i][2]+ brd[i][3]+
brd[i][4]+ brd[i][5]+ brd[i][6]+ brd[i][7]+ brd[i][8]+ brd[i][9]+
brd[i][10]+ brd[i][11]+ brd[i][12]+ brd[i][13]+ brd[i][14]);
}
} // end of printPattern
public static void dropDisk(String[][] brd, int position, int
player) {
if (player == 1){
brd[6][position] = "R";
if(brd[6][position] == "R"){
brd[6][position] = brd[6 - 1][position];
}
}
else if (player == 2){
brd[6][position] = "Y";
if(brd[6][position] == "Y"){
brd[6][position] = brd[6 - 1][position];
}
}
/*Write your code to drop the disk at the position the user entered
depending on which player*/
} // end of dropDisk
The logic of dropDisk seems to be not finished yet.
It sets the brd[6][position] to R or Y, just to immediately after that set it to the current value of brd[5][position].
And this should always be null.
In Java, objects are passed into methods by value. This means that when you pass a parameter into a function, the JVM makes a copy of that object which can be modified in the method.
In this case, when you pass brd into dropDisk, it is copied, and you make changes to the copy inside dropDisk. But once dropDisk ends, that copy is discarded. No changes are made to the board from your main method. This is because your board is an array of Strings, and Strings are immutable, meaning that they cannot be changed after instantiation.
If you wanted the board from your main method to update, consider returning brd in dropDisk.

I keep getting error: cannot find symbol when I compile my code [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 4 years ago.
When I run my code I get "error: cannot find symbol" when it gets to
tile = board.get(col-1); //get tile.
I've tried taking the board arraylist out of the constructor, but then I get error: < identifier > expected when it get's to board = b.getBoard();. I don't know what I'm doing wrong. I'm terrible at coding so any help is really appreciated.
import java.util.ArrayList;
/**
*The game class holds data about the game
*/
public class Game
{
private int row; //row
private int col; //columb
//create array list of rows
ArrayList<Integer> rows = new ArrayList<>();
//create array list of columbs
ArrayList<Integer> columbs = new ArrayList<>();
//create array list of selected tiles
ArrayList<Tile> selected = new ArrayList<>();
private int index = 0; //set index to 0
/**
This constructor sets up a game board
*/
public Game()
{
//create new Board
Board b = new Board();
//create array list tiles of type Tile
ArrayList<Tile> board = new ArrayList<>();
//call Board's getBoard method
board = b.getBoard();
}
/**
This constructor sets columb and row variabules
*/
public Game(int r, int c)
{
row = r; //row of tile being tested
col = c; //columb of tile being tested
}
/**
isValidSelection method takes the columb and row of
a tile and returns a boolean value for if the tile is
adjacent to the previous tile or not
#param the row of the tile
#param the columb of the tile
#return true if tile is adjacent t previous tile
*/
public boolean isValidSelection(int row, int col)
{
//check if array is empty (no previous tile)
if (rows.isEmpty())
{
rows.add(row); //add to rows array
columbs.add(col); //add to columbs array
return true; //return that tile is adjacent
}
else
{
//check if tile is adjacent to previous
if (Math.abs(rows.get(index)-row)<=1)
{
rows.add(row); //add to rows array
columbs.add(col); //add to columbs array
return true; //return that tile is adjacent
}
//check if tile is adjacent to previous
else if (Math.abs(columbs.get(index)-col)<=1)
{
rows.add(row); //add to rows array
columbs.add(col); //add to columbs array
return true; //return that tile is adjacent
}
//case if tile is not adjacent
else
{
return false; //return that tiles aren't adjacent
}
}
index += 1; //add 1 to index
}
/**
addToSelected method takes the columb and row of a
tile and adds them to array of selected tile row and col
#param the row of the tile
#param the columb of the tile
*/
public void addToSelected(int row, int col)
{
if (row == 1)
{
Tile tile; //tile
tile = board.get(col-1);//get tile
selected.add(tile); // add to selected
}
else if (row == 2)
{
Tile tile; //tile
tile = board.get(col+3);//get tile
selected.add(tile); // add to selected
}
else if (row == 3)
{
Tile tile; //tile
tile = board.get(col+7);//get tile
selected.add(tile); // add to selected
}
else
{
Tile tile; //tile
tile = board.get(col+11);//get tile
selected.add(tile); // add to selected
}
}
/**
removeFromSelected method takes the columb and row of a tile
and deletes them from array of selected tile row and col
#param the row of the tile
#param the columb of the tile
*/
public void removeFromSelected(int row, int col)
{
if (row == 1)
{
Tile tile; //tile
tile = board.get(col-1);//get tile
selected.add(tile); // add to selected
}
else if (row == 2)
{
Tile tile; //tile
tile = board.get(col+3);//get tile
selected.add(tile); // add to selected
}
else if (row == 3)
{
Tile tile; //tile
tile = board.get(col+7);//get tile
selected.add(tile); // add to selected
}
else
{
Tile tile; //tile
tile = board.get(col+11);//get tile
selected.add(tile); // add to selected
}
}
/**
toString method
#return A string containing the board
*/
public String toString()
{
// Create a string representing the board
String str = board.get(0) + board.get(1) +
board.get(2) + board.get(3) + "\n"+
board.get(4) + board.get(5) +
board.get(6) + board.get(7) + "\n"+
board.get(8) + board.get(9) +
board.get(10) + board.get(11) + "\n"+
board.get(12) + board.get(13) +
board.get(14) + board.get(15);
//return the string
return str;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class BoggleText {
public static void main(String[] args) {
// create game
Game g = new Game();
// create scanner for user input
Scanner keyboard = new Scanner(System.in);
// variables for user input
int row, col;
String input;
// create flag to end game
boolean stop = false;
while (!stop) {
// print board
System.out.println(g);
// prompt user for choices
System.out.print("(s)elect, (d)eselect, (l)ist selected, " +
"(c)lear selected, (t)est selected, (e)nd: ");
// get choice
input = keyboard.nextLine();
// select
if (input.equalsIgnoreCase("s")) {
// prompt for row & column
System.out.print("row / column [r c]: ");
// get row, col from input
row = keyboard.nextInt();
col = keyboard.nextInt();
input = keyboard.nextLine(); // clr new line left in buffer
// test if the r/c combination is a valid move
if (g.isValidSelection(row, col)){
// add tile to selected tiles
g.addToSelected(row, col);
}
else {
System.out.println("Invalid selection! Please select " +
"a letter adjacent to the previously " +
"selected letter.");
}
}
// deselect
else if (input.equalsIgnoreCase("d")) {
// prompt for row & column
System.out.print("row / column [r c]: ");
// get row, col from input
row = keyboard.nextInt();
col = keyboard.nextInt();
input = keyboard.nextLine(); // clr new line left in buffer
// remove tile from selected tiles
g.removeFromSelected(row,col);
}
// list currently selected tiles
else if (input.equalsIgnoreCase("l")) {
ArrayList<Tile> selected = g.getSelectedTiles();
System.out.println(selected);
}
// clear currently selected tiles
else if (input.equalsIgnoreCase("c")) {
g.clearSelected();
}
else if (input.equalsIgnoreCase("t")) {
g.testSelected();
}
// end game
else if (input.equalsIgnoreCase("e")) {
stop = true;
}
}
}
}
I haven't finished writing out game class, but boggletext should be right
It is exactly like Compass says. If you want to access your variable Board 'b', you should define Board b outside constructor, and then initialize inside your constructor.
public class Game{
...
private Board b;
...
public Game(){
b = new Board();
...
}
}

Cards shuffle in gridlayout when I Click on a button in the grid

This is my first time using this site so don't go hard on me
I'm trying to make my own card game and in the game, the cards are placed in a 6 x 9 gridlayout. Everything else I can handle, but there is one feature in the game that I'm having trouble on, and if I can get it to work, I'll be finished. This is for my final project and it's due in about 5 days
I'm trying to make the cards shuffle when the user clicks on the White Joker card.
When that White Joker is clicked, the faced up cards and the other poker cards that are faced down are shuffled too. I don't want any duplicate cards in the grid
To be more explicit, I'll show my problem visually, because what I'm trying to do is complicated to explain in words and also complicated to make the code for it.
When the user clicks on one or more faced down cards, it'; look something like this:
When the White Joker is clicked it was shuffled and I don't want it to shuffle. I want everything else to shuffle while the White Joker stays in it's spot.
Here is my shuffle method code. Below I want this method to shuffle the JButtons but not the White Joker one. The White Joker one should stay
public JButton[] whiteJokerShuffle(JButton[] button)
{
//shuffles using fisher yates shuffle BUT ONLY White Joker does not
//shuffle
//FIX THISSSSSSSSSSSSSSSSSSSSSSS
Random rand = new Random();
int randomCard;
JButton randomValue;
for (int i = 0; i<button.length; i++)
{
randomCard = rand.nextInt(button.length);
//can't find a way to check for White Joker and make it stay
randomValue = button[randomCard];
button[randomCard] = button[i];
button[i] = randomValue;
}
return button;
}
And again, I do not want to see duplicate poker cards when I shuffle the cards and click on the buttons. I keep making that happen every time I try, and I don't know how to fix it so here is my other code that creates the frame and stuff:
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.GridLayout;
/**
*
* #author elngo
*/
public class GameFrame extends JFrame {
private final int FRAME_WIDTH = 900;
private final int FRAME_HEIGHT = 730;
private int _attempts = 0;
private GridLayout _buttonMatrix;
private ImageIcon _image;
private ImageIcon _faceDownImage;
private JButton[] _button;
private ActionListener _listener;
private JPanel _gridPanel;
private JOptionPane _introduction; //this pops up BEFORE the gamem starts
private JOptionPane _endGameResult; //this ONLY pops up when the game ENDS
//using the Cards class
private Cards _cards;
private String[] _pokerDeck;
private JButton _whiteJoker;
final int GRID_ROWS = 6;
final int GRID_COLUMNS = 9;
//Constructor
/**
*
*/
public GameFrame()
{
frameComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
/**
*
*/
private void frameComponents()
{
_cards = new Cards(); //invokes Cards class
String[] faceDown = _cards.getFaceDown();
_pokerDeck = _cards.getPokerDeck();
//makes a matrix of JButtons
_button = new JButton[_pokerDeck.length];
_gridPanel = new JPanel(_buttonMatrix = new GridLayout(GRID_ROWS, GRID_COLUMNS));
_listener = new ClickListener();
//places FACE DOWN cards in the 6x9 grid first
for (int i = 0; i<faceDown.length; i++)
{
_faceDownImage = new ImageIcon(faceDown[i]);
_gridPanel.add(_button[i] = new JButton(_faceDownImage)); //adds to grid
_button[i].addActionListener(_listener);
}
add(_gridPanel);
//shuffle poker cards
//comment this randomizer out UNTIL I find a way to make WhiteJoker work
//_cards.shuffleDeck(_pokerDeck);
}
public class ClickListener implements ActionListener{
#Override
/**
*
*/
public void actionPerformed(ActionEvent event)
{
for (int i=0; i<_button.length; i++)
{
if (event.getSource() == _button[i])
{
_image = new ImageIcon(_pokerDeck[i]);
_button[i].setIcon(_image);
_attempts++;
System.out.println("Attempts: " + _attempts); //delete later
//***THE WHITE JOKER SHUFFLE PROBLEM STARTS HERE***
if (_pokerDeck[i] == "WJ.png") //if White Joker clicked
{
//FIX THISSSSSSSSSSSSSSSsssSSSSSSSSSssssSs
System.out.println("White Joker found"); //delete later
//save off Joker Spot so iterate through _buttonMatrix
String whiteJoker = _pokerDeck[i];
for (int j = 0; j<_button.length; j++)
{
if (_button[j] != null)
{
//***THE SHUFFLE METHOD I SHOWED IS USED BELOW***
_cards.whiteJokerShuffle(_button);
}
}
_gridPanel.removeAll();
for (JButton button : _button)
{
_gridPanel.add(button);
}
_gridPanel.revalidate();
_gridPanel.repaint();
}
//***PROBLEM STOPS HERE***
I really need help on this. Just this one complicated problem, and once it's solved, I'll tidy up my code and I'll be finished.
You can implement a modified version of the Fisher–Yates shuffle (or the modern version, designed for computer use, that was introduced by Richard Durstenfeld in 1964 and popularized by Donald E. Knuth):
When the White Joker is to be shuffled, you leave it on the same position.
When one of the other cards is to be shuffled, you make sure it is not swapped with the White Joker.
In the actionPerformed method, you iterate over all the buttons and then detect that the White Joker is clicked. The loop variable i contains the index of the White Joker, which you do not want to change. This value can be passed to the modified shuffle method.
To keep the example below short, I have passed an array of strings (instead of buttons) and determined the index of the White Joker inside the shuffle method:
import java.util.*;
public class GameFrame {
private static final String WHITE_JOKER_CODE = "*W";
public static void main(String[] arguments) {
String[] originalCards = {"5H", "5C", "6S", WHITE_JOKER_CODE, "7S", "KD"};
System.out.println("Original cards: " + Arrays.toString(originalCards));
String[] shuffledCards = new GameFrame().whiteJokerShuffle(originalCards);
System.out.println("Shuffled cards: " + Arrays.toString(shuffledCards));
}
// Uses the modern version of the Fisher–Yates shuffle, designed for computer use,
// as introduced by Richard Durstenfeld in 1964 and popularized by Donald E. Knuth.
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
public String[] whiteJokerShuffle(String[] cards)
{
int whiteJokerIndex = Arrays.asList(cards).indexOf(WHITE_JOKER_CODE);
Random randomNumbers = new Random();
for (int cardIndex = cards.length - 1; cardIndex > 0; cardIndex--)
{
if (cardIndex != whiteJokerIndex) {
// The upper bound is normally one higher than cardIndex, but it is
// lowered by one when the white joker is in the range (to "hide" it).
boolean hideJoker = cardIndex > whiteJokerIndex;
int upperBound = cardIndex + (hideJoker ? 0 : 1);
int swapIndex = randomNumbers.nextInt(upperBound);
if (swapIndex == whiteJokerIndex) {
swapIndex++;
}
// Swap the cards on indices swapIndex and cardIndex.
String swapCard = cards[swapIndex];
cards[swapIndex] = cards[cardIndex];
cards[cardIndex] = swapCard;
}
}
return cards;
}
}

How to Sort the Cards. (Is my code wrong?)

Not sure if I need to edit this class or not since the cards ARE changing. Just not in order
import java.lang.Integer;
/**
* This class is used to keep track of playing cards.
*
* #author (name)
* #version (date)
*/
public class Card implements Comparable<Card>
{
public int compareTo(Card otherCard) {
// instance variables - replace the example below with your own
private String denom, suit;
/**
* Card is to be passed in as a denomination and suit
*/
public Card(String description)
{
description = description.toUpperCase();
if( description.length() == 2)
{
suit = description.substring(1);
denom = description.substring(0,1);
} else if(description.length() == 3) {
suit = description.substring(2);
denom = description.substring(0,2);
} else {
System.out.print("Error: An invalid card code was given.");
}
}
/**
* This will give a string that states a description of the card.
* #return Card description as a string.
*/
public String getDis()
{
//get the description
String denomMessage = denom;
if(denom.equals("A"))
denomMessage = "Ace";
else if(denom.equals("K"))
denomMessage = "King";
else if(denom.equals("Q"))
denomMessage = "Queen";
else if(denom.equals("J"))
denomMessage = "Jack";
//get the suit
String suitMessage = suit;
if(suit.equals("S"))
suitMessage = "Spades";
else if(suit.equals("D"))
suitMessage = "Dimonds";
else if(suit.equals("C"))
suitMessage = "Clubs";
else if(suit.equals("H"))
suitMessage = "Hearts";
else
suitMessage = "There was a problem";
return denomMessage + " of " + suitMessage;
}
/**
* This was written for the purpose of helping to select a card image.
* #return clubs are 1, hearts are 2, spades are 3, diamonds are 4
*/
public int numSuit()
{
int value = 0;
if(suit.equals("C"))
value = 1;
else if(suit.equals("H"))
value = 2;
else if(suit.equals("S"))
value = 3;
else if(suit.equals("D"))
value = 4;
return value;
}
/**
* This class was written for the purpose of selecting a card image
* #return ace is a 1, jack is a 11, queen is a 12, king is a 13
*/
public int numDenom()
{
int value = 0;
if(denom.equals("A"))
value = 1;
else if(denom.equals("J"))
value = 11;
else if(denom.equals("Q"))
value = 12;
else if(denom.equals("K"))
value = 13;
else
value = Integer.parseInt(denom);
return value;
}
/**
* Are the two cards the same suit and denomination?
* #return true or false
*/
public boolean equals(Card a)
{
if(denom.equals(a.denom) && suit.equals(a.suit))
return true;
else
return false;
}
/**
* I would suggest that you write this method
*/
public int denomCompareTo(Card a)
{
return a.numDenom() - numDenom();
}
}
All it's doing is changing it's card to the lowest card entered. I have to make it go in order from smallest to largest. no matter what face.
import java.awt.*;
import java.io.*;
import java.applet.*;
import java.awt.image.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* This applet is currently working. It will run in a webpage. It will take in card codes such as
* 2h for the two of heart and "paint" the image of five cards when all five text fields each have a
* card coding entered into them. Your assignment will be to write the part of the code
* that will sort the cards once they have been entered so that the will be "painted" from smallest
* to largest denomination regardless of suit as long "None" is selected in the drop down box. In
* the event one of the suits is selected that suit will be placed in order first then followed by
* the rest of the cards in order. To complete the assignment you should read through this class' code
* but you will only need to change the section that state that you should change it and possibly
* the card class.
*
* #author (Put your name here.)
* #version (Put the date here.)
*/
public class CardApplet extends Applet {
Image ic1,ic2,ic3,ic4,ic5;
Card c1,c2,c3,c4,c5;
private TextField cardIn1,cardIn2,cardIn3,cardIn4,cardIn5;
private String message;
private Button enter,sort;
private ButtonListener buttonListen;
private Choice trump;
static final int CARD_WIDTH = 73;
static final int CARD_HEIGHT = 98;
/**
* This is called an inner class as it is a class writen inside of another class. It is here so
* that the buttons will be able to trigger an event.
*/
class ButtonListener implements ActionListener
{
/**
* The name of this method is important and should not be changed. This will take in the
* "action" of a button being pushed and store reference to it in the object variable e.
*/
public void actionPerformed(ActionEvent e)
{
String action = e.paramString();
if( action.indexOf("Enter") >= 0)
{
//get text
String text1 = cardIn1.getText();
String text2 = cardIn2.getText();
String text3 = cardIn3.getText();
String text4 = cardIn4.getText();
String text5 = cardIn5.getText();
//Get rid of whitespace before and after string
text1 = text1.trim();
text2 = text2.trim();
text3 = text3.trim();
text4 = text4.trim();
text5 = text5.trim();
message = "Cards Entered";
//setup cards and card images
c1 = new Card(text1);
ic1 = getCardImage(c1);
c2 = new Card(text2);
ic2 = getCardImage(c2);
c3 = new Card(text3);
ic3 = getCardImage(c3);
c4 = new Card(text4);
ic4 = getCardImage(c4);
c5 = new Card(text5);
ic5 = getCardImage(c5);
//this method call is to this class and tells the applet to follow the code of paint again.
repaint();
}
else if( action.indexOf("Sort") >= 0)
{
//ADD YOUR CODE HERE.
if(c1.denomCompareTo(c2) < 0 )
ic1 = ic2;
c1 = c2;
if(c1.denomCompareTo(c3) < 0 )
ic1 = ic3;
c1 = c3;
if(c1.denomCompareTo(c4) < 0 )
ic1 = ic4;
c1 = c4;
if(c1.denomCompareTo(c5) < 0 )
ic1 = ic5;
c1 = c5;
if(c2.denomCompareTo(c1) < 0 )
ic2 = ic1;
c2 = c1;
if(c2.denomCompareTo(c3) < 0 )
ic2 = ic3;
c2 = c3;
if(c2.denomCompareTo(c4) < 0 )
ic2 = ic4;
c2 = c4;
if(c2.denomCompareTo(c5) < 0 )
ic2 = ic5;
c2 = c5;
if(c3.denomCompareTo(c1) < 0 )
ic3 = ic1;
c3 = c1;
if(c3.denomCompareTo(c2) < 0 )
ic3 = ic2;
c3 = c2;
if(c3.denomCompareTo(c4) < 0 )
ic3 = ic4;
c3 = c4;
if(c3.denomCompareTo(c5) < 0 )
ic3 = ic5;
c3 = c5;
if(c4.denomCompareTo(c1) < 0 )
ic4 = ic1;
c4 = c1;
if(c4.denomCompareTo(c2) < 0 )
ic4 = ic2;
c4 = c2;
if(c4.denomCompareTo(c3) < 0 )
ic4 = ic3;
c4= c3;
if(c4.denomCompareTo(c5) < 0 )
ic4 = ic5;
c4 = c5;
if(c5.denomCompareTo(c1) < 0 )
ic5 = ic1;
c5 = c1;
if(c5.denomCompareTo(c2) < 0 )
ic5 = ic2;
c5 = c2;
if(c5.denomCompareTo(c3) < 0 )
ic5 = ic3;
c5 = c3;
if(c5.denomCompareTo(c4) < 0 )
ic5 = ic4;
c5 = c4;
//DO NOT CHANGE CODE PAST THIS LINE.
message = "Sorted";
repaint();
}
}
} //end of inner class.
/**
* This method is called when the applet is first started. It will setup the layout of the applet.
*/
public void init() {
//This is the text that prints in the gray box towards the bottem of the applet.
message="Let us get started ";
//Sets the back ground color of the the applet
setBackground(Color.GREEN);
// Set default layout manager
setLayout(new FlowLayout() );
//setup textboxes for entering in cards
cardIn1 = new TextField("Enter",4);
add(cardIn1);
cardIn2 = new TextField("cards ",4);
add(cardIn2);
cardIn3 = new TextField("using",4);
add(cardIn3);
cardIn4 = new TextField("Chap 5",4);
add(cardIn4);
cardIn5 = new TextField("coding",4);
add(cardIn5);
//place buttons
buttonListen = new ButtonListener();
enter = new Button("Enter");
enter.addActionListener(buttonListen);
add(enter);
sort = new Button("Sort");
sort.addActionListener(buttonListen);
add(sort);
//setup dropdown
trump = new Choice();
trump.addItem("None");
trump.addItem("Hearts");
trump.addItem("Diamonds");
trump.addItem("Spades");
trump.addItem("Clubs");
add(trump);
//Since the card object variables are null each image object variable
//will hold reference to a card back image.
ic1 = getCardImage(c1);
ic2 = getCardImage(c2);
ic3 = getCardImage(c3);
ic4 = getCardImage(c4);
ic5 = getCardImage(c5);
}
/*
* This class is used to place graphics on an applet.
*/
public void paint(Graphics g) {
//places cards on applet
int linePos = 70;
g.drawImage(ic1,19,linePos,this);
g.drawImage(ic2,19+CARD_WIDTH,linePos,this);
g.drawImage(ic3,19+2*CARD_WIDTH,linePos,this);
g.drawImage(ic4,19+3*CARD_WIDTH,linePos,this);
g.drawImage(ic5,19+4*CARD_WIDTH,linePos,this);
// simple text displayed on applet
g.setColor(Color.lightGray);
g.draw3DRect(2, 175, 200, 20, true);
g.fillRect(2, 175, 200, 20);
g.setColor(Color.black);
g.drawString(message, 4, 190);
}
/**
* This will select either the correct portion of the cards image based on the suit and denomination or
* the card back image.
* #param a The card object holds the suit and denomination in state.
* #return It returns an image object variable with holds reference to a image that was created for a card that was passed in.
* #throws MalformedURLException
*/
public Image getCardImage(final Card a)
{
int cardDenom,cardSuit;
Image playingCards = null;
ImageFilter cardFilter;
ImageProducer cardProducer;
if( a == null)
{
playingCards = getImage(getCodeBase(), "cardBack.png");
}else{
playingCards = getImage(getCodeBase(),"cards.png");
cardDenom = (a.numDenom()*CARD_WIDTH)- CARD_WIDTH;
cardSuit = (a.numSuit()*CARD_HEIGHT) - CARD_HEIGHT;
cardFilter = new CropImageFilter(cardDenom,cardSuit,CARD_WIDTH,CARD_HEIGHT);
cardProducer = new FilteredImageSource(playingCards.getSource(),cardFilter);
playingCards = createImage(cardProducer);
}
return playingCards;
}
}
nIcE cOw is correct in mentioning Comparable
from http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Which means that your implementation of Comparable for your objects (cards) should follow that convention.
In your top code section
public int denomCompareTo(Card a)
{
if ( a.numDenom() < this.numDenom() ) //the value of card a is less
{ return -1; }
else if ( a.numDenom() == this.numDenom() ) //equality
{ return 0; }
else //otherwise.. whatever's left (a must be greater)
{ return 1;}
}
Read that over until you understand it. Comparable is the method you want to definitely work. It's going to be invoked by calling
FirstCard.CompareTo( SecondCard );
that line of code is going to return a value of either -1, 0, or 1. Depending on which is greater, or 0 if they are equal. That's all a sorting algorithm really /needs/ to be able to figure out an ordering.
So that's the code you need for Comparable. Please look it over until you understand it.
The code in the second portion,
else if( action.indexOf("Sort") >= 0)
{
//ADD YOUR CODE HERE.
...
}
Needs to be updated to reflect how Comparable works.
So I am guessing this is a button or action thingy, and if you specify Sort then we want to sort the cards. Fair enough. Well, where are the cards stored? It looks like in a bunch of variables named c(number) and ic(number) for the image. Like c1 and ic1, c2 and ic2. In the future, look into using arrays.
So your code is almost correct for this portion! It's just that you need a temporary value to store the old card. Otherwise you're overwriting it everytime.
For example: First basket is an apple, Second basket is a grape.
If you say "Hey, put the contents of the 2nd basket into the 1st" then the first one becomes grape. The second one is also (still) grape. Where did apple go? We lost it because computers are mercilessly true to your instructions. We need to store the old card in a new variable.
So when you say
if(c1.denomCompareTo(c2) < 0 ) { //for the love of jobe please use braces for multiline if statements
ic1 = ic2;
c1 = c2;
}
The original ic1 and c1 are being overwritten and lost.
You can fix this by using a temporary variable or swapping variable, or when you get really clever, using XOR (ask your nerdy friends)
Image tempImg;
Card tempCard;
if(c1.denomCompareTo(c2) < 0 ) { //meaning if card1 is less than card2
tempImg = ic1; //store card1 temporarily
tempCard = c1;
ic1 = ic2; //copy vals of card2 to card1 slots
c1 = c2;
ic2 = tempImg; //slide the original val of ic1 here
c2 = tempCard;
}
Granted, your sorting algorithm is accurate, but will require many passes if the cards are in any funky ordering. Which is why you'll probably have to loop over these instructions several times. You're doing something incrementally usually referred to as "bubble sort" ... If you need help looping over your sorting, just let us know.
Here are some examples:
I am posting a very quick reference example for you to look at. It is not that tough to understand, though, once you will understand it, things will become a bit more easier.
import java.util.*;
enum Suit {
HEART,
DIAMOND,
CLUB,
SPADE
}
class Card implements Comparable<Card> {
private int rank;
private Suit suit;
public Card ( int rank, Suit suit ) {
this.rank = rank;
this.suit = suit;
}
public int getRank () {
return rank;
}
public void setRank ( int rank ) {
this.rank = rank;
}
public Suit getSuit () {
return suit;
}
public void setSuit ( Suit suit ) {
this.suit = suit;
}
#Override
public int compareTo ( Card anotherCard ) {
return this.rank - anotherCard.rank;
}
#Override
public String toString () {
return String.format ("Suit: %8s Rank: %8s", suit, rank);
}
}
public class CardsExample {
private static final int TOTAL_CARDS = 52;
private static final int CARDS_PER_SUIT = 13;
private static final int TOTAL_SUITS = 4;
private List<Card> deck;
public CardsExample () {
deck = new ArrayList<Card> ();
}
private void createDeck () {
for ( Suit suit : Suit.values () ) {
for ( int i = 0; i < CARDS_PER_SUIT; ++i ) {
deck.add ( new Card ( i, suit ) );
}
}
}
private void displayDeck () {
for ( Card card : deck ) {
System.out.println ( card );
}
}
private void performTask () {
createDeck ();
Collections.shuffle ( deck );
System.out.println ( "Before SORTING" );
displayDeck ();
Collections.sort ( deck );
System.out.println ( "After SORTING" );
displayDeck ();
}
public static void main ( String[] args ) {
new CardsExample ().performTask ();
}
}
EDIT:
If one wants to sort cards, in terms of their Suit first, then one can use Comparatortoo, in this example, for which not much of a change is required, just change the enum part, as shown below and provide implementation for Comparator < Card >, within the Cardclass, and let Collections.sort ( deck, suitComparator )do the work, as shown in this example.
import java.util.*;
enum Suit {
HEART ( 0 ),
DIAMOND ( 1 ),
CLUB ( 2 ),
SPADE ( 3 );
private int value;
private Suit ( int value ) {
this.value = value;
}
public int retrieveValue () {
return value;
}
}
class Card implements Comparable < Card > {
private int rank;
private Suit suit;
public static Comparator < Card > suitComparator =
new Comparator < Card > () {
#Override
public int compare ( Card someCard, Card anotherCard ) {
return someCard.suit.retrieveValue () - anotherCard.suit.retrieveValue ();
}
};
public Card ( int rank, Suit suit ) {
this.rank = rank;
this.suit = suit;
}
public int getRank () {
return rank;
}
public void setRank ( int rank ) {
this.rank = rank;
}
public Suit getSuit () {
return suit;
}
public void setSuit ( Suit suit ) {
this.suit = suit;
}
#Override
public int compareTo ( Card anotherCard ) {
return this.rank - anotherCard.rank;
}
#Override
public String toString () {
return String.format ( "Suit: %8s Rank: %8s", suit, rank );
}
}
public class CardsExample {
private static final int TOTAL_CARDS = 52;
private static final int CARDS_PER_SUIT = 13;
private static final int TOTAL_SUITS = 4;
private List < Card > deck;
public CardsExample () {
deck = new ArrayList < Card > ();
}
private void createDeck () {
for ( Suit suit : Suit.values () ) {
for ( int i = 0; i < CARDS_PER_SUIT; ++i ) {
deck.add ( new Card ( i, suit ) );
}
}
}
private void displayDeck () {
for ( Card card : deck ) {
System.out.println ( card );
}
}
private void performTask () {
createDeck ();
Collections.shuffle ( deck );
System.out.println ( "Before SORTING" );
displayDeck ();
Collections.sort ( deck );
Collections.sort ( deck, Card.suitComparator );
System.out.println ( "After SORTING" );
displayDeck ();
}
public static void main ( String[] args ) {
new CardsExample ().performTask ();
}
}
Good luck

Getting error "package X does not exist" in Java

import java.util.*; ...
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Item");
This is my Java code. The final line gets the error: "package stringList does not exist".
How can I get rid of this error and start adding items to my list? I can only imagine I'm missing something very simple. Thanks in advance.
Partially per request, below is my whole code. It's incomplete, but I'm stuck on the above problem.
package gorobot_m5d25y2013;
//import java.util.List;
import java.util.ArrayList;
class Engine { // The Engine will show the best positions on the board given a particular board setup.
// Some project-wide constants and variables.
final int BLACK = 1; // Black go pieces... black goes first in the game of go, unless black has
// a 2 stone or greater handicap.
final int WHITE = 2; // White go pieces... usually goes second in the game.
final int EMPTY = 0; // An empty space, no piece is on it.
final int VIRTUAL = -1; // This is a space outside of the board that can never be played on,
// but is useful if there's ever an issue of checking something for
// the board which would normally be out of bounds.
final int BLACKS_TURN = 1;
final int WHITES_TURN = 2;
final int BOARD_SIZE = 19; // Access with Global.BOARD_SIZE ... this is the width of the board.
final int VIRTUAL_BOARD_BORDER = 10; // This is the width of the empty space around each of the four sides of the board.
int whoseTurn; // 1 is blacks turn, 2 is white's turn.
int totalGames = 0;
int blackWins = 0;
static long groupCounter = 1; // Used in inner class group.
int positionNumber = 1; // Used in inner class group and position.
int[][] boardValues = new int[BOARD_SIZE][BOARD_SIZE]; // boardValues is the win probability for each position on the board.
Engine() {
Board firstMove = new Board();
}
int oppositeWhoseTurn() {
int opposite = 0;
if (whoseTurn == BLACKS_TURN) {
opposite = WHITES_TURN;
}
if (whoseTurn == WHITES_TURN) {
opposite = BLACKS_TURN;
}
if (opposite == 0) {
System.out.println("An error with the opposite variable has occured.");
}
return opposite;
}
int regPos(int boardPosition) { // This Regulates Position-Ex. takes any of the normal board positions, for example,
// 1-19, and sets it to the virtual, larger board. So a Position 1 move will be position 9 with a 10 space buffer.
int realBoardPosition = (boardPosition + (VIRTUAL_BOARD_BORDER - 1));
return realBoardPosition;
}
class Board { // The board is composed of positions and groups. At first it is 2 groups, the real and the virtual
int virtualPlusRegularBoardSize = (BOARD_SIZE + (VIRTUAL_BOARD_BORDER * 2));
Position[][] point = new Position[virtualPlusRegularBoardSize][virtualPlusRegularBoardSize];
Group food = new Group();
Board() {
for (int horizontal = 0; horizontal < virtualPlusRegularBoardSize; horizontal++) {
for (int vertical = 0; vertical < virtualPlusRegularBoardSize; vertical++) {
point[horizontal][vertical] = new Position(horizontal, vertical);
}
}
for (int horizontal = 1; horizontal <= BOARD_SIZE; horizontal++) {
for (int vertical = 1; vertical <= BOARD_SIZE; vertical++) {
point[regPos(horizontal)][regPos(vertical)].setType(EMPTY);
}
}
}
}
class Group { // Each Group is composed of positions
long groupNumber;
int sizeOfGroup = 1;
Integer[] ints = new Integer[1];
ArrayList<String> stringList = new ArrayList<String>();
stringList.add ("Item");
//List<Position> positionList = new ArrayList<>();
//positionList.size ();
//positionList.add ();
//positionList.remove("F");
Group() {
groupNumber = groupCounter;
groupCounter++;
}
void setGroupNumber(int newGroupNumber) {
sizeOfGroup = newGroupNumber;
}
long getGroupNumber() {
return groupNumber;
}
void setSizeOfGroup(int newGroupSize) {
sizeOfGroup = newGroupSize;
}
int getSizeOfGroup() {
return sizeOfGroup;
}
void addPositionToGroup(Position point) {
}
}
class Position { // Each position is either Empty, Black, White, or Virtual.
int pieceType; // VIRTUAL means it's not even a board position, at first all spaces are like this...
// but eventually, the positions on the actual board will all be empty - 0, and then
// will start filling with black - 1 and white - 2 pieces.
boolean legalMove; // This tells us whether this space is a legal move.
int numberOfLiberties = 2;
int virtualHorizontal;
int virtualVertical;
Position() {
pieceType = VIRTUAL;
legalMove = false;
}
Position(int horizontal, int vertical) {
pieceType = VIRTUAL;
legalMove = true;
virtualHorizontal = horizontal;
virtualVertical = vertical;
}
void setType(int setType) {
pieceType = setType;
////// Add in here the 4 surrounding sides and make those these variables accessible from the piece class.
if (setType == BLACK) {
}
if (setType == WHITE) {
}
}
int getType() {
return pieceType;
}
}
}
/**
*
* #author Eric Martin
*/
public class GoRobot_m5d25y2013 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Engine firstEngine = new Engine();
}
}
And these are my errors:
run:
Exception in thread "main" java.lang.ClassFormatError: Method "<error>" in class gorobot_m5d25y2013/Engine$Group has illegal signature "(Ljava/lang/Object;)LstringList/add;"
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at gorobot_m5d25y2013.Engine$Board.<init>(GoRobot_m5d25y2013.java:73)
at gorobot_m5d25y2013.Engine.<init>(GoRobot_m5d25y2013.java:46)
at gorobot_m5d25y2013.GoRobot_m5d25y2013.main(GoRobot_m5d25y2013.java:181)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
From your edit, the problem is that you're calling stringList.add("Item"); in the class definition. The execution of methods from your class fields should be done inside a method. In your case, looks like this line should be inside your class constructor:
class Group { // Each Group is composed of positions
//fields definitions (and probably initialization of fields)...
//field declaration
ArrayList<String> stringList = new ArrayList<String>();
//this code can't be here
//stringList.add("Item");
Group() {
//move it here
stringList.add("Item");
//...
}
//rest of code...
}
This code is not generating any error and I think you have not put it in the class.You can try this.
import java.util.*;
public class One {
public static void main(String args[]) {
ArrayList<String> stringList=new ArrayList<String>();
stringList.add("Europe");
System.out.println(stringList);
}
}
You should create an object of Group.
Then use that object to access the list.
In main method try
Group g = new Group();
g.stringList.add("item");

Categories