I've made a card game, similar to solitaire. It's almost finished. The last thing I'm struggling with is printing top 5 scores. Whenever player ends a game it writes into scores.txt file how many piles he's left on a table, let's say 4. So in the .txt file I have following numbers: 1,2,3,4,5,6,7,8,9. How can I print from file top 5 of these, so it's: 1,2,3,4,5.
DeckOfCards class:
import java.io.*;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class DeckOfCards {
private ArrayList<Cards> deck;
private int currentCard=-1; //index of the next card to be dealt
private Scanner in;
private int i;
//ArrayList<Integer> indexesToRemove = new ArrayList();
/**
*
* Constructor to build a deck of cards
*/
public DeckOfCards() {
this.deck = new ArrayList<Cards>();
}
public void removeCard(int i) {
this.deck.remove(i);
}
public Cards getCard(int i){
return this.deck.get(i);
}
public void addCard(Cards addCards){
this.deck.add(addCards);
}
//Draws from the deck1
public void draw(DeckOfCards comingFrom){
currentCard++;
this.deck.add(comingFrom.getCard(0));
comingFrom.removeCard(0);
}
public void saveScore(){
try (PrintStream out = new PrintStream(new FileOutputStream("scores.txt"))) {
out.print(deck.size());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Card class:
public class Cards {
private String suit;
private String value;
public Cards(String suit, String value)
{
this.suit = suit;
this.value = value;
}
public String getSuit() {
return suit;
}
public void setSuit(String suit) {
this.suit = suit;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
#Override
public String toString() {
return suit + value;
}
}
Hope it helps. I got rid of some methods I believe they aren't useful. There's also the menu and like I said every case works except of displaying top 10 results.
1 - Print the pack out (this is so you can check that it plays properly)
2 - Shuffle
3 - Deal a card
4 - Make a move, move last pile onto previous one
5 - Make a move, move last pile back over two piles
6 - Amalgamate piles in the middle (by giving their numbers)
7 - Print the displayed cards on the command line
8 - Play for me once (if two possible moves, makes the ‘furthest’ move)
9 - Play for me many times
10 - Display top 10 results
When the game is over, read the input file in memory (like in a list), add the new result at the position it should go in the leaderboard, write the new results in the file, then take the five first of the list (element 0 is best score and element n is worst score).
public void endGame(int finalScore) throws IOException {
List<String> scores = retrieveScores();
addNewScore(finalScore, scores);
writeScores(scores);
showLeaderBoard(scores);
}
private List<String> retrieveScores() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("score.txt"));
String scoreLine = reader.readLine(); // read line that contains scores
List<String> scores = new ArrayList<>();
if (scoreLine != null) { // in case of first game
String[] tempScore = scoreLine.split(", ");
scores = new ArrayList<>(Arrays.asList(tempScore));
}
reader.close();
return scores;
}
private void addNewScore(int finalScore, List<String> scores) {
boolean foundSpotForNewScore = false;
int i = 0;
while (!foundSpotForNewScore && i < scores.size()) {
if (finalScore <= Integer.parseInt(scores.get(i))) {
foundSpotForNewScore = true;
}
i++;
}
scores.add(i, String.valueOf(finalScore));
}
private void writeScores(List<String> scores) throws IOException {
FileWriter writer = new FileWriter("score.txt");
String outputScores = scores.toString();
outputScores = outputScores.replace("[", "");
outputScores = outputScores.replace("]", "");
writer.write(outputScores);
writer.close();
}
private void showLeaderBoard(List<String> scores) {
System.out.println("*** TOP 5 LEADERBOARD ***");
int i = 0;
while (i < 5 && i < scores.size()) {
System.out.println(scores.get(i));
i++;
}
System.out.println("*** TOP 5 LEADERBOARD ***");
}
Related
Suppose given a class Die and it contains a random value for a six sided die.
Another class PairOfDice needs to access getvalue in Die and store two die values.
An error: cannot find symbol occurs when PairOfDice is executed.
How can this problem be fixed? And are there any other suggestions for the java code?
public class Die {
public static Random rand = new Random();
private int sides; // Number of sides
private int value; // Die's value
public Die() {
sides = 6;
roll();
}
public void roll() {
value = rand.nextInt(sides) + 1;
}
public int getSides() {
return sides;
}
public int getValue() {
return value;
}
The second class given is:
public class PairOfDice {
private int dieOne;
private int dieTwo;
public void main(String[] args){
Die die;
die = new Die();
}
private void dieOne(int value){
dieOne = die.getValue();
}
private void dieTwo(int value){
dieTwo = die.getValue();
}
public int getDieOneValue(){
return dieOne;
}
public int getDieTwoValue(){
return dieTwo;
}
}
This quest should be generalized:
I wrote the Die class with two public constructors. If the constructor is without the parameter, default size of die is six, else you can have any number of sides.
Then, I wrote the Dices class with two constructors. First one have the number of dices (with 6 sides), and second one have the List of dices with preferred sides.
If you want to learn how to generalize the problem (any problem) you can check my code. (Of course, it can be done more efficiently and with more elegance, but here is the simple code):
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Die {
private Random RAND = new Random();
private int noOfSides;
private int value;
// Default constructor without the parameter of sides gives the six sized die
public Die() {
this.noOfSides = 6;
}
// The constructor WITH number of sides
public Die(int noOfSides) {
this.noOfSides = noOfSides;
}
// rolling the die
public void roll() {
this.value = RAND.nextInt(noOfSides) + 1;
}
public int getValue() {
if (value == 0) roll(); // if the die is never rolled -> roll it!
// else return the rolled value
return value;
}
// just for curiosities
public int getNoOfSides() {
return noOfSides;
}
public String toString() {
return "Die has the " + noOfSides + " sides, and the last roll value was " + getValue();
}
}
class Dices {
private int noOfDices;
private List<Die> myDices = new ArrayList<Die>();
// NO constructor without the number of dices
private Dices() {
}
public Dices(int noOfDices) {
this.noOfDices = noOfDices;
// example is for 6 sided dices
for (int i = 0; i < noOfDices; i++) {
getMyDices().add(new Die());
}
}
// example with the list of dices with predefined sizes
public Dices(List<Die> myDices){
this.myDices = myDices;
}
public List<Die> getMyDices() {
return myDices;
}
public String toString() {
String s = "";
for (Die die : getMyDices()) {
s = s + die + "\n";
}
return s;
}
}
public class Answer {
public static void main(String[] args) {
//test with two dices (6 size):
Dices twoDices = new Dices(2);
System.out.println(twoDices);
//test with 4 dices size 3, 7, 9, 22
Dices fourDices = new Dices
(List.of(new Die(3),
new Die(7),
new Die(9),
new Die(22)));
System.out.println(fourDices);
}
}
You can see, if the die is never rolled, getValue first roll the die, then return the value. Otherwise you can roll the die and the value will be stored into the private field value...
We will presume that the Die class works as expected.
So, one could think of these changes to PairOfDice that likely resolve the immediate issue.
public class PairOfDice {
private Die dieOne = new Die();
private Die dieTwo = new Die();
public static void main(String[] args) {
PairOfDice pair = new PairOfDice();
System.out.printf("Pair: %d - %d%n", pair.getDieOneValue(), pair.getDieTwoValue());
}
public int getDieOneValue() {
dieOne.roll();
return dieOne.getValue();
}
public int getDieTwoValue() {
dieTwo.roll();
return dieTwo.getValue();
}
}
The PairOfDice class should hold references to two dice (in the private Die instance variables).
The getDieXValue() methods work with the instance variables, and return a value, after generating a roll().
Now, the question is whether the requirement is to store the values of two dice, or just access to the ability to get the values. If truly the need is to store the values, then one could do:
public class PairOfDice {
private int dieOneValue;
private int dieTwoValue;
public PairOfDice {
Die die = new Die();
// get a value for the first die
die.roll();
dieOneValue = die.getValue();
// get a value for the 2nd die
die.roll();
dieTwoValue = die.getValue();
}
public int getDieOneValue() {
return dieOneValue;
}
...
Personally, if one is going to create objects, then store and use the objects.
This question already has answers here:
Unreported exception java.sql.SQLException; must be caught or declared to be thrown? [duplicate]
(4 answers)
Closed 6 years ago.
No idea what I'm doing wrong. If I could get some help that would be fantastic. Here's the class with the error:
import java.util.Scanner;
/** The solitaire card game Idiot's Delight. */
public class IdiotsDelight {
/** For reading from the console. */
public static final Scanner INPUT = new Scanner(System.in);
/** The four Stacks of Cards. */
private Stack<Card>[] stacks;
/** The Deck of Cards. */
private Deck deck;
/** Create and shuffle the Deck. Deal one Card to each Stack. */
public IdiotsDelight() {
deck = new Deck();
deck.shuffle();
stacks = new Stack[4]; // This causes a compiler warning
for (int i = 0; i < 4; i++) {
stacks[i] = new ArrayStack<Card>();
}
deal();
}
/** Deal one Card from the Deck onto each Stack. */
public void deal() {
for (Stack<Card> s : stacks) {
s.push(deck.deal());
}
}
/** Play the game. */
public void play() {
while (true) {
// Print game state
System.out.println("\n" + this);
// Check for victory
boolean done = true;
for (Stack<Card> s : stacks) {
if (!(s.isEmpty())) {
done = false;
break;
}
}
if (done) {
System.out.println("You win!");
return;
}
// Get command
System.out.print("Your command (pair, suit, deal, or quit)? ");
String command = INPUT.nextLine();
// Handle command
if (command.equals("pair")) {
removePair();
} else if (command.equals("suit")) {
removeLowCard();
} else if (command.equals("deal")) {
deal();
} else {
return;
}
}
}
/**
* Remove the lower of two Cards of the same suit, as specified by
* the user.
*/
public void removeLowCard() throws IllegalMoveException {
System.out.print("Location (1-4) of low card? ");
int i = INPUT.nextInt();
System.out.print("Location (1-4) of high card? ");
int j = INPUT.nextInt();
INPUT.nextLine(); // To clear out input
stacks[i - 1].pop();
}
/**
* Remove two Cards of the same rank, as specified by the user.
*/
public void removePair() throws IllegalMoveException {
System.out.print("Location (1-4) of first card? ");
int i = INPUT.nextInt();
System.out.print("Location (1-4) of second card? ");
int j = INPUT.nextInt();
INPUT.nextLine(); // To clear out input
stacks[i - 1].pop();
stacks[j - 1].pop();
}
public String toString() {
String result = "";
for (int i = 0; i < 4; i++) {
if (stacks[i].isEmpty()) {
result += "-- ";
} else {
result += stacks[i].peek() + " ";
}
}
return result + "\n" + deck.size() + " cards left in the deck";
}
/** Create and play the game. */
public static void main(String[] args) {
System.out.println("Welcome to Idiot's Delight.");
IdiotsDelight game = new IdiotsDelight();
game.play();
}
}
Error is in the play() method, specifically on these 2 lines with the same error:
removePair();
removeLowCard();
IllgalMoveException class just in case it's needed:
/** Thrown when a player attempts an illegal move in a game. */
public class IllegalMoveException extends Exception {
}
Catch an exception using try-catch block, like this:
//...
try{
removePair();
}catch(IllegalMoveException e){
//...
}
//...
//...
try{
removeLowCard();
}catch(IllegalMoveException e){
//...
}
//...
I have made two classes, one is called Card, and the other is Pack.
The Card class has the following attributes :
private String Name;
private int Magic;
private int Cunning;
private int Courage;
private int Wisdom;
private int Temper;
In the Pack class, I have made a file reader methods that read a file on my PC and store each line of it as a string array. So for example this is a part of the text (not code):
Pansy_Parkinson
42
21
18
19
9
Dean_Thomas
40
10
35
22
4
My String array[] stores each line as a different index.
What I want to do, is to convert this String array to array of type Card.
It should store in each index a card with the 6 attributes..
So I suppose I will need to have a method to convert it, and I will have my new 2D Card array based on the previous text this way:
Card [][] ArrayOfCards = new Card [1][5];
Please, any idea how I can do this?
..........................................................
..........................................................
Thank you very much everyone for your valuable helps!
I tried all codes and they seemed great! but I don't know why it's showing me errors either in my main or the methods themselves..
Here is my FileReader class!
import java.io.File;
import java.util.Arrays;
import java.io.*; //To deal with exceptions
import java.util.*;
import java.util.Scanner;
import java.util.ArrayList;
public class ReadFile {
private Scanner x;
private String Path;
public ReadFile (String ThePath){
Path = ThePath;
}
public String[] openFile() throws IOException /*To throw any errors up the line*/
{
FileReader FR = new FileReader(Path);
BufferedReader TextReader = new BufferedReader(FR);
int NoOfLines = readLines();
String[] TextData = new String[NoOfLines];
for (int i = 0; i < NoOfLines; i++)
TextData[i] = TextReader.readLine(); //Accesses the lines of text and stores them in the array
TextReader.close();
return TextData;
}
int readLines() throws IOException //Return the number of lines in the text
{
FileReader FR2 = new FileReader(Path);
BufferedReader BF = new BufferedReader(FR2);
String ALine;
int NoOfLines = 0;
while ((ALine = BF.readLine()) != null)//Read each line of text & stop when a null value's reached
NoOfLines++;
BF.close();
return NoOfLines;
}
}
And I have just read it yet on main as like this:
public static void main(String[] args) {
// TODO code application logic here
String FileName = "C:/Users/Anwar/Desktop/Potter.txt"; //Path of the file on my PC
try {
ReadFile File = new ReadFile(FileName);
String[] ArrayLines = File.openFile();
for(int i = 0; i < ArrayLines.length; i++)
System.out.println(ArrayLines[i]);
}
catch (IOException e) /*Defiend object of type IOException*/ {
System.out.println(e.getMessage());
}}
Anyone can help me in this?
Because you have a c# tag with your question I decided to give a c# example, which you should be able to convert over to java fairly easily.
Essentially I've created a Card class which has a constructor that accepts the 6 stats about the card. I've kept the fields private as this is how they are in your Question.
I've create a for loop that runs through each of the items in the array, effectively taking 6 items at a time and passing them through to the Card constructor. We're then adding this card to our List of Cards.
I also threw in a quick ToInt() extension to tidy up the Card instantiation.
There are going to be better ways of doing this, but this solves the problem you have presented us with. There is also no error handling in this example.
class Program
{
static void Main(string[] args)
{
var rawData = new string[]{
"Pansy_Parkinson",
"42",
"21",
"18",
"19",
"9",
"Dean_Thomas",
"40",
"10",
"35",
"22",
"4"
};
var Cards = new List<Card>();
for(int i = 0; i < rawData.Length; i+=6)
{
var card = new Card(rawData[0 + i], rawData[1 + i].ToInt(), rawData[2 + i].ToInt(), rawData[3 + i].ToInt(), rawData[4 + i].ToInt(), rawData[5 + i].ToInt());
Cards.Add(card);
}
}
}
public static class StringExtensions
{
public static int ToInt(this string item)
{
return Convert.ToInt32(item);
}
}
public class Card
{
private string Name;
private int Magic;
private int Cunning;
private int Courage;
private int Wisdom;
private int Temper;
public Card(string name, int magic, int cunning, int courage, int wisdom, int temper)
{
Name = name;
Magic = magic;
Cunning = cunning;
Courage = courage;
Wisdom = wisdom;
Temper = temper;
}
}
Maybe try to od it like that:
Create constructor for Card with param String array[][] and which will be the array created from text file and second param which will be the int number that will say where to search for the data for constructor
the constructor should work like this:
Card(String[][] array, int numberForConstructor){
this.name = array[numberForConstructor][0];
this.magic = array[numberForConstructor][1];
this.cunning = array[numberForConstructor][2];
this.courage = array[numberForConstructor][3];
this.temper = array[numberForConstructor][4];
}
then you can use this constructor to put new Card objects to Array, List or anything you want
You should create getter/setter for your class Card, then you can use this function. I don't know which language you use (c# or java) so you will have to adjust the solution bellow.
public class Pack
{
public List<Card> cards = new List<Card>();
public Pack(string filename)
{
// Your parsing function
while ((line = readLine() != null)
{
Card c = new Card();
c.setName(line);
c.setMagic(Convert.ToInt32(readLine());
c.setCunning(Convert.ToInt32(readLine());
c.setCourage(Convert.ToInt32(readLine());
c.setWisdom(Convert.ToInt32(readLine());
c.setTemper(Convert.ToInt32(readLine());
cards.add(c);
}
}
}
Then you to create a new Pack just do the following
Pack p = new Pack("cards.txt");
p.cards[0].getName();
It seams that your input array has one card parameter per line. So I think you are simply looking for something like this:
public static Card[] convert(String[] arr){
if(arr.length % 6 != 0){
System.out.println("error in data");
return null;
}
Card[] res = new Card[arr.length / 6];
for(int i = 0; i < res.length; i++){
String Name = arr[(i * 6) + 0];
int Magic = Integer.parseInt(arr[(i * 6) + 1]);
int Cunning = Integer.parseInt(arr[(i * 6) + 2]);
int Courage = Integer.parseInt(arr[(i * 6) + 3]);
int Wisdom = Integer.parseInt(arr[(i * 6) + 4]);
int Temper = Integer.parseInt(arr[(i * 6) + 5]);
res[i] = new Card(Name, Magic, Cunning, Courage, Wisdom, Temper);
}
return res;
}
This can work:
public Card ConvertArrayToCard(string[] array)
{
Card card = new Card;
card.Name = array[0];
card.Magic= array[1];
card.Cunning= array[2];
card.Courage= array[3];
card.Wisdom= array[4];
card.Temper= array[5];
}
Quite a few answers.. Here is another one.
Your class;
public class Pack
{
public string Name { get; set; }
public int Magic { get; set; }
public int Cunning { get; set; }
public int Courage { get; set; }
public int Wisdom { get; set; }
public int Temper { get; set; }
}
Then the logic. There is some built in defensive coding mechanism in this. I will let you figure that out.
var lines = File.ReadAllLines(#"C:\temp2.txt");
List<Pack> mypack = new List<Pack>();
Pack member = null;
int count = 0;
foreach (var line in lines)
{
int val;
count = (!int.TryParse(line, out val)) ? 0 : count + 1;
switch (count)
{
case 0:
member = new Pack() { Name = line.Trim() };
break;
case 1:
member.Magic = val;
break;
case 2:
member.Cunning = val;
break;
case 3:
member.Courage = val;
break;
case 4:
member.Wisdom = val;
break;
case 5:
member.Temper = val;
mypack.Add(member);
break;
}
}
return mypack;
Question:
How do I update numberOfWins in the db as the program runs(rounds of poker are played), & at the end of program execution, display the data in/from my db?
Background:
This is a fairly standard console based poker game. Table is a dealer(creates hands) & executes rounds. PokerGameMain, the main. I also have classes for Card, Deck, Player, Wallet. 3 players are dealt cards, creating a hand, the hands are played, there is a winner & looser, this is a round. I have included my current code on these classes for context.
My questions are about two database/JDBC/SQLite classes(SQLiteJDBC, Database) I am attempting to implement. I've added these solely for learning purposes. I'm attempting to gain knowledge of database/JDBC/SQLite & maven(which I have used to manage my SQLite dependency).
I've working pretty diligently at this program but I'm having a little trouble seeing how to pull it together.
Question Again:
Primary) How do I:
Create a db(poker)...done I think.
Create a table(players), with 2 columns(palyerName, numberOfWins)...done I think.
Create 3 rows(player1-3)...done I think.
Update numberOfWins in the db as the program runs(rounds of poker are played), & at the end of program execution, display the data in my db
Secondary) Suggestions regarding:
My exception handling & design in SQLiteJDBC & Database
SQLiteJDBC
Note:
The only errors in the program that I know of are an unchecked exception & a can not resolve method. Both in SQLiteJDBC, here & here:
try {
db.execute(dropTable);
db.execute(createTable);
db.execute(insertInto1);
db.execute(insertInto2);
db.execute(insertInto3);
ResultSet resultSets = db.executeQuery(selectFrom);
try {
while (resultSets.next()) {
// read the result set
System.out.println("player = " + resultSets.getString("playerName"));
System.out.println("number of wins = " + resultSets.getInt("numberOfWins"));
}
}
try {
db.close();
}
package com.craigreedwilliams.utilities;
import java.sql.*;
/**
* Created by Reed on 7/10/2015.
*/
public class SQLiteJDBC {
public static void passQuery() {
String dropTable = "DROP TABLE if EXISTS players";
String createTable = "CREATE TABLE players(VARCHAR(25) playerName, INTEGER numberOfWins)";
String insertInto1 = "INSERT INTO player1 VALUES ('player1', 0)";
String insertInto2 = "INSERT INTO player2 VALUES ('player2', 0)";
String insertInto3 = "INSERT INTO player3 VALUES ('player3', 0)";
String selectFrom = "SELECT * FROM players";
// Url for SqlLite
String jdbcDbType = "jdbc:sqlite";
String dbName = "poker.db";
String dbUrl = jdbcDbType + ":" + dbName;
Database db = new Database(dbUrl);
try {
db.execute(dropTable);
db.execute(createTable);
db.execute(insertInto1);
db.execute(insertInto2);
db.execute(insertInto3);
ResultSet resultSets = db.executeQuery(selectFrom);
try {
while (resultSets.next()) {
// read the result set
System.out.println("player = " + resultSets.getString("playerName"));
System.out.println("number of wins = " + resultSets.getInt("numberOfWins"));
}
}
finally {
try {
resultSets.close();
}
catch (Exception ignore) {
}
}
}
finally {
try {
db.close();
}
catch (Exception ignore) {
}
}
}
}
Database
package com.craigreedwilliams.utilities;
import java.sql.*;
/**
* Created by Reed on 7/10/2015.
*/
public class Database {
public String dbUrl;
private String sqliteDriver = "org.sqlite.JDBC";
private String driver;
private Connection connection = null;
private Statement statement = null;
public Database() {
}
public Database(String dbUrl) {
this.dbUrl = dbUrl;
// sqliteDriver = getDriverString(dbUrl);
try {
setConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
private void setConnection() throws Exception {
try {
// registered DriverName using the current class loader
Class.forName(sqliteDriver);
}
catch (Exception e) {
// connection failed
System.out.println("DriverName: " + driver + " was not available");
System.err.println(e);
throw e;
}
// create a database connection
connection = DriverManager.getConnection(dbUrl);
try {
statement = connection.createStatement();
}
catch (Exception e) {
try {
connection.close();
}
catch (Exception ignore) {
}
connection = null;
}
}
// this method should undoubtedly be public as we'll want to call this
// to close connections externally to the class
public void closeConnection() {
if (statement!=null) {
try {
statement.close();
}
catch (Exception ignore) {
}
}
if (connection!=null) {
try {
connection.close();
}
catch (Exception ignore) {
}
}
}
// and we will definitely want to be able to call the following two
// functions externally since they expose the database
// behaviour which we are trying to access
public ResultSet executeQuery(String query) throws SQLException {
return statement.executeQuery(query);
}
public void execute(String query) throws SQLException {
statement.executeUpdate(query);
}
}
PokerGameMain
package com.craigreedwilliams.game;
import java.util.Scanner;
/**
* Hello world!
*
*/
public class PokerGameMain
{
public static void main(String[] args) {
//Input Object of the scanner class
Scanner input = new Scanner(System.in);
int choice;
System.out.println("Welcome to Poker Table! May the odds forever be in your favor :)");
do {
printMainGameWelcomeMenu();
choice = input.nextInt();
switch (choice){
case 1:
//call start game method or class here
startGame();
break;
case 2:
//end game here
printMainGameGoodbyeMessage();
break;
default:
System.out.println("The value you entered is outside of the range required for this application...");
}
} while (choice != 2);
}
public static void printMainGameWelcomeMenu(){
System.out.println("This is the poker game's menu: \n"
+ "To start the game enter: 1\n"
+ "To end game enter: 2\n");
}
public static void printMainGameGoodbyeMessage(){
System.out.println("Thank you for playing the poker game! Hope you enjoyed your experience. Have a great day! :D");
}
public static void startGame(){
int count = 1;
Table table = new Table();
getUserInput(table);
while (count < 4) {
System.out.println("Round : " + count + "...\n");
table.dealCards();
table.showCards();
count++;
}
}
public static void getUserInput(Table table){
Scanner usrInput = new Scanner(System.in);
boolean anteSet = false;
System.out.println("Before the game starts, I will need some information...\n");
System.out.println("What is your name?");
String name = usrInput.nextLine();
//set player name
table.getPlayerAt(0).setPlayerName(name);
// set ante
do {
System.out.println("How much are you willing to bet for every round? Keep in mind there will have to be at least three rounds...");
Double ante = usrInput.nextDouble();
if(checkAnte(ante, table.getPlayerAt(0).getWallet())) {
table.getPlayerAt(0).setAnteValue(ante);
anteSet = true;
}
}while (!(anteSet));
}
public static boolean checkAnte(double ante, Wallet wallet){
if (ante * 3.0 > wallet.getBalance()) {
System.out.println("Sorry your wallet balance is less than you think...Please reconsider the ante value");
return false;
}
else
{
wallet.deductFromBalance(ante);
System.out.println("Your ante for each round is set to be: " + ante + ". Good luck!");
return true;
}
}
}
Table
package com.craigreedwilliams.game;
/**
* Created by Reed on 7/10/2015.
*/
public class Table {
// two private attributes
private Player[] players;
private Deck deck;
private double pot;
private Player winner;
/******************************************
** The array is set in the following way:
******************************************
** pairs are each given 1 point **
** three of a kind are given 3 points **
** straights are given 5 points **
** flush are given 7 points **
** four of a kind are given 8 points **
** royal straights are given 10 points **
** royal flush are given 12 points **
******************************************
*/
private int[][] game = new int [7][2];
// constructor initializes the deck and cards
public Table() {
deck = new Deck();
players = new Player[3];
players[0] = new Player();
players[1] = new Player();
players[2] = new Player();
deck.shuffle();
}
// getter for player at the given index
public Player getPlayerAt(int index){
return players[index];
}
// deals the card to each player
public void dealCards() {
int count = 0;
for (int i = 0; i < players[0].getCards().length; i++) {
for (int j = 0; j < players.length; j++) {
players[j].setCardAtIndex(deck.getCard(count++), i);
}
}
}
// simulates the game and shows the result
public void showCards() {
for (int i = 0; i < players.length; i++) {
System.out.print("Player " + (i + 1) + ": \n");
for (int j = 0; j < players[0].getCards().length; j++) {
System.out.println("{" + players[i].getCardAtIndex(j).toString() + "} ");
}
if(players[i].countPair() > 0) {
System.out.println("Pair(S):" + players[i].countPair() + "! \n");
game[0][i] += players[i].countPair();
}
if(players[i].isFlush()) {
System.out.println("Flush! ");
}
if(players[i].isRoyalFlush())
System.out.println("Royal Flush!!\n");
if(players[i].isThreeOfAkind())
System.out.println("Three of a kind! ");
if(players[i].isFourOfAkind())
System.out.println("Four of a kind!!\n");
if(players[i].isStraight())
System.out.println("Straight! \n");
if(players[i].isRoyalStraight())
System.out.println("Royal Straight!!\n");
else
System.out.print("\n");
}
}
}
Wallet
package com.craigreedwilliams.game;
import java.util.Random;
/**
* Created by Reed on 7/11/2015.
*/
public class Wallet {
private double balance;
/**
* default Wallet constructor
*/
public Wallet() {
setRandomStartingBalance(50.0, 500.0);
}
private void setRandomStartingBalance(double minimum, double maximum) {
Random random = new Random();
double randomStartingBalance = minimum + (maximum - minimum) * random.nextDouble();
balance = randomStartingBalance;
}
public double getBalance() {
return balance;
}
public void deductFromBalance(double price) {
this.balance = balance - price;
}
}
Player
package com.craigreedwilliams.game;
/**
* Created by Reed on 7/10/2015.
*/
public class Player {
private final static int MAX = 5;
private Card cards[]; //hand
private Deck tempDeck = new Deck();
private Double anteValue = 0.0;
private Wallet wallet;
private String playerName = "";
int gamesWon = 0;
// private bools for checks
private boolean pair = false;
private boolean threeOfAkind = false;
private boolean fourOfAkind = false;
private boolean royalStraight = false;
private boolean royalFlush = false;
//constructor initializes 5 cards in each hand
public Player() {
cards = new Card[MAX];
wallet = new Wallet();
}
// getters are setters for name and ante value
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public Double getAnteValue() {
return anteValue;
}
public void setAnteValue(Double anteValue) {
this.anteValue = anteValue;
}
// getter for wallet for player object
public Wallet getWallet() {
return wallet;
}
// getter and setter for games won so far...
public int getGamesWon() {
return gamesWon;
}
public void setGamesWon(int gamesWon) {
this.gamesWon = gamesWon;
}
//returns all the cards in hand
public Card[] getCards() {
return cards;
}
//get the cards at a particular position
public Card getCardAtIndex(int index) {
return (index >= 0 && index < MAX) ? cards[index] : null;
}
//sets the card at particular position
public void setCardAtIndex(Card c, int index) {
if(index >= 0 && index < MAX)
cards[index] = c;
}
// basic bool return functions
public boolean isRoyalStraight() {
return royalStraight;
}
public boolean isThreeOfAkind() {
return threeOfAkind;
}
public boolean isFourOfAkind() {
return fourOfAkind;
}
public boolean isRoyalFlush() {
return royalFlush;
}
//Main Logic here : public functions that check for all winning hands and change private boolean variables
// appropriately
//counts number of matched pair
public int countPair() {
int count = 0;
//boolean pairCheck = ((!(threeOfAkind) && (!(fourOfAkind))));
for (int i = 0; i < cards.length; i++) {
for (int j = i + 1; j < cards.length; j++)
{
if (cards[i].getRank().equals(cards[j].getRank())){
count++;
if (count == 1)
pair = true;
else if ((pair) && (count == 3)) {
threeOfAkind = true;
pair = false;
}
else if ((threeOfAkind) && (count == 4)) {
fourOfAkind = true;
threeOfAkind = false;
}
}
}
}
return (pair) ? count : 0;
}
//checks if it is a flush or not i.e all five cards of same suit also checks for royal flush
public boolean isFlush()
{
int count = 0;
for (int i = 0; i < cards.length; i++) {
for (int j = i + 1; j < cards.length; j++) {
if (cards[i].getSuit().equals(cards[j].getSuit())) {
count++;
}
}
if (count == 5){
if (cards[i].getRankInt() == tempDeck.getRankInt(12))
royalFlush = true;
}
}
return ((count == 5) && (!(royalFlush))) ? true : false;
}
//checks to see if it is a straight or royal straight or neither
public boolean isStraight(){
int count = 0;
for (int i = 0; i < cards.length - 1; i++){
if ((cards[i].getRankInt() + 1 == cards[i + 1].getRankInt()) && (count < 4)){
count++;
}
else if (count == 4){
if (cards[i].getRankInt() == tempDeck.getRankInt(13)){
royalStraight = true;
}
}
}
return ((count == 4) && (!(royalStraight))) ? true : false;
}
}
Deck
package com.craigreedwilliams.game;
import java.util.Calendar;
import java.util.Random;
/**
* Created by Reed on 7/10/2015.
*/
public class Deck {
private final String rank[] = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King", "Ace"};
private final String suits[]={"Hearts","Diamonds","Clubs","Spades"};
private final int rankInt[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
private final int suitsInt[] = {1, 2, 3, 4};
private Card deck[];
private final int MAX = 52;
private Random randNum;
//makes the deck, constructor - no arguments
public Deck() {
deck = new Card[MAX];
//uses calendar object to get time stamp
Calendar cal = Calendar.getInstance();
long seed = cal.getTimeInMillis();
randNum = new Random(seed); // random generated using time seed
// uses modulus operator
for(int i = 0; i < deck.length; i++ ){
deck[i] = new Card( rank[i % 13], suits[i / 13], rankInt[i % 13], suitsInt[i / 13]);
}
}
//shuffles the deck
public void shuffle(){
for(int i = 0; i < deck.length; i++ ){
int j = randNum.nextInt(MAX);
Card c = deck[i];
deck[i] = deck[j];
deck[j] = c;
}
}
//returns the individual card in the deck
public Card getCard(int index){
return deck[index];
}
//returns rankInt from the deck object at the given index value
public int getRankInt(int index) {
return rankInt[index];
}
}
Card
package com.craigreedwilliams.game;
/**
* Created by Reed on 7/10/2015.
*/
public class Card {
private String rank;
private String suit;
private int rankInt;
// TODO: remove this if actually never used
private int suitInt;
//four argument constructor initializes Cards rank and suit (stings and ints)
public Card(String rank, String suit, int rankInt, int suitInt) {
super();
this.rank = rank;
this.suit = suit;
this.rankInt = rankInt;
this.suitInt = suitInt;
}
//getter method to return the rank value
public String getRank() {
return rank;
}
//getter method to return the suit value
public String getSuit() {
return suit;
}
//setter method to initialize the suit
public int getRankInt() {
return rankInt;
}
//return String representation of Card object
public String toString() {
return rank + " : " + suit;
}
}
Your SQL query should look like this:
Select Player,Wins From yourtable Set Wins=Wins + 1 Where Player=playerid
The columns are just examples because I don't know how you called them ;)
And at the end of each round you just need to query your SQL-Server.
I have to make a program that reads each word a file and makes an index of which lines the word occurs on in alphabetical order.
for example, if the file had:
a white white dog
crowded around the valley
the output should be:
a
around: 2
crowded: 2
dog: 1
the: 2
valley: 1
white: 1, 1
When my file contains:
one fish two fish blue fish green fish
cow fish milk fish dog fish red fish
can you find a little lamb
can you find a white calf
THE OUTPUT IS WRONG!: (NOT IN ALPHA ORDER)
a: 3 4
calf: 4
find: 3 4 4
lamb: 3
little: 3
white: 4
you: 3 4
blue: 1
can: 3
cow: 2
dog: 2
green: 1 1 2 2 2 2
milk: 2
red: 2
two: 1 1 1
fish: 1
one: 1
Here is my code::
INDEXMAKER MASTER CLASS
import java.io.*;
import java.util.*;
public class IndexMaker {
private ArrayList<Word> words;
private String fileName;
private String writeFileName;
public IndexMaker(String fileName, String writeFileName) {
this.fileName = fileName;
this.writeFileName = writeFileName;
words = new ArrayList<Word>();
}
public void makeIndex() {
try {
File file = new File(fileName);
Scanner lineScanner = new Scanner(file);
int lineNum = 0;
while (lineScanner.hasNext()) {
lineNum++;
Scanner wordScanner = new Scanner(lineScanner.nextLine());
while (wordScanner.hasNext()) {
String word = wordScanner.next().toLowerCase();
if (!words.contains(new Word(word))) {
insertInto(word, findPosition(word), lineNum);
} else {
addLineNum(word, lineNum);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void displayIndex() {
try {
//FileWriter fileWriter = new FileWriter(new File(writeFileName));
//BufferedWriter writer = new BufferedWriter(fileWriter);
for (Word word : words)
System.out.println(word.getWord() + ": " + word.getLineNums());
} catch (Exception e) {
}
}
private int findPosition(String word) {
for (int i = 0; i < words.size(); i++) {
if (word.compareTo(words.get(i).getWord()) <= 0)
return i;
}
return 0;
}
private void insertInto(String word, int pos, int lineNum) {
words.add(pos, new Word(word, String.valueOf(lineNum)));
}
private void addLineNum(String word, int lineNum) {
int pos = findPosition(word);
words.get(pos).addLineNum(lineNum);
}
}
WORD CLASS
public class Word {
private String word;
private String lineNums;
public Word(String word, String lineNum) {
this.word = word;
this.lineNums = lineNum;
}
public Word(String word) {
this.word = word;
this.lineNums = "";
}
public String getWord() {
return word;
}
public String getLineNums() {
return lineNums;
}
public void addLineNum(int num) {
lineNums += " " + num;
}
#Override
public boolean equals(Object w) {
if (((Word)w).getWord().equals(word))
return true;
else
return false;
}
}
CLIENT
public class Client {
public static void main(String[] args) {
IndexMaker indexMaker = new IndexMaker("readme.txt", "readme.txt");
indexMaker.makeIndex();
indexMaker.displayIndex();
}
}
any help would be appreciated, thanks.
I can't find your definition of compareTo. It seems this would be the key part of your program?
Properly implement your compareTo and confirm it works properly by printing the results of comparisons using System.out.println
Doing your own comparison is "ok" in that it will work if you do it properly. The other thing you could do would be to implement Comparable and then you can get Java to sort a list of words for you.