Java, JDBC: Updating & displaying values in/from SQLite db -


question:

how update numberofwins in db program runs(rounds of poker played), & @ end of program execution, display data in/from db?

background:

this standard console based poker game. table dealer(creates hands) & executes rounds. pokergamemain, main. have classes card, deck, player, wallet. 3 players dealt cards, creating hand, hands played, there winner & looser, round. have included current code on these classes context.

my questions 2 database/jdbc/sqlite classes(sqlitejdbc, database) attempting implement. i've added these solely learning purposes. i'm attempting gain knowledge of database/jdbc/sqlite & maven(which have used manage sqlite dependency).

i've working pretty diligently @ program i'm having little trouble seeing how pull together.

question again:

primary) how i:

  • create db(poker)...done think.

  • create table(players), 2 columns(palyername, numberofwins)...done think.

  • create 3 rows(player1-3)...done think.

  • update numberofwins in db program runs(rounds of poker played), & @ end of program execution, display data in db

secondary) suggestions regarding:

  • my exception handling & design in sqlitejdbc & database

sqlitejdbc

note:

the errors in program know of unchecked exception & 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 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 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 player1 values ('player1', 0)";         string insertinto2 = "insert player2 values ('player2', 0)";         string insertinto3 = "insert player3 values ('player3', 0)";         string selectfrom = "select * players";          // url 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 result set                     system.out.println("player = " + resultsets.getstring("playername"));                     system.out.println("number of wins = " + resultsets.getint("numberofwins"));                 }             }             {                 try {                     resultsets.close();                 }                 catch (exception ignore) {                 }             }         }         {             try {                 db.close();             }             catch (exception ignore) {             }         }     } } 

database

package com.craigreedwilliams.utilities;  import java.sql.*;  /**  * created 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 current class loader             class.forname(sqlitedriver);         }         catch (exception e) {             // connection failed             system.out.println("drivername: " + driver + " not available");             system.err.println(e);             throw e;         }         // create database connection         connection = drivermanager.getconnection(dburl);         try {             statement = connection.createstatement();         }         catch (exception e) {             try {                 connection.close();             }             catch (exception ignore) {             }             connection = null;         }     }      // method should undoubtedly public we'll want call     // close connections externally class     public void closeconnection() {         if (statement!=null) {             try {                 statement.close();             }             catch (exception ignore) {             }         }         if (connection!=null) {             try {                 connection.close();             }             catch (exception ignore) {             }         }     }      // , want able call following 2     // functions externally since expose database     // behaviour trying 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 scanner class         scanner input = new scanner(system.in);          int choice;          system.out.println("welcome poker table! may odds forever in favor :)");            {              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 entered outside of range required application...");              }          } while (choice != 2);      }       public static void printmaingamewelcomemenu(){          system.out.println("this poker game's menu: \n"                 + "to start game enter: 1\n"                 + "to end game enter: 2\n");     }      public static void printmaingamegoodbyemessage(){          system.out.println("thank playing poker game! hope enjoyed experience. have 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 game starts, need information...\n");          system.out.println("what name?");         string name = usrinput.nextline();          //set player name         table.getplayerat(0).setplayername(name);           // set ante         {             system.out.println("how willing bet every round? keep in mind there have @ least 3 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 wallet balance less think...please reconsider ante value");             return false;         }         else         {             wallet.deductfrombalance(ante);             system.out.println("your ante each round set be: " + ante + ". luck!");             return true;         }      } } 

table

package com.craigreedwilliams.game;  /**  * created reed on 7/10/2015.  */ public class table {     // 2 private attributes     private player[] players;     private deck deck;     private double pot;     private player winner;       /******************************************      ** array set in following way:      ******************************************      **  pairs each given 1 point        **      **  3 of kind given 3 points  **      **  straights given 5 points        **      **  flush given 7 points            **      **  4 of kind given 8 points   **      **  royal straights given 10 points **      **  royal flush given 12 points     **      ******************************************      */     private int[][] game = new int [7][2];      // constructor initializes deck , 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 player @ given index     public player getplayerat(int index){         return players[index];     }      // deals card each player     public void dealcards() {         int count = 0;         (int = 0; < players[0].getcards().length; i++) {             (int j = 0; j < players.length; j++) {                 players[j].setcardatindex(deck.getcard(count++), i);             }         }     }      // simulates game , shows result     public void showcards() {         (int = 0; < players.length; i++) {             system.out.print("player " + (i + 1) + ": \n");             (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 kind! ");             if(players[i].isfourofakind())                 system.out.println("four of 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 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 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 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 setters name , 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 wallet player object     public wallet getwallet() {         return wallet;     }      // getter , setter games won far...     public int getgameswon() {         return gameswon;     }      public void setgameswon(int gameswon) {         this.gameswon = gameswon;     }      //returns cards in hand     public card[] getcards() {         return cards;     }      //get cards @ particular position     public card getcardatindex(int index) {         return (index >= 0 && index < max) ? cards[index] : null;     }      //sets card @ 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 check winning hands , change private boolean variables     //                  appropriately      //counts number of matched pair     public int countpair() {          int count = 0;         //boolean paircheck = ((!(threeofakind) && (!(fourofakind))));          (int = 0; < cards.length; i++) {             (int j = + 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 flush or not i.e 5 cards of same suit checks royal flush     public boolean isflush()     {         int count = 0;         (int = 0; < cards.length; i++) {             (int j = + 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 see if straight or royal straight or neither     public boolean isstraight(){         int count = 0;          (int = 0; < 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 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 deck, constructor - no arguments     public deck() {         deck = new card[max];          //uses calendar object time stamp         calendar cal = calendar.getinstance();         long seed = cal.gettimeinmillis();          randnum = new random(seed); // random generated using time seed          // uses modulus operator         for(int = 0; < deck.length; i++ ){             deck[i] = new card( rank[i % 13], suits[i / 13], rankint[i % 13], suitsint[i / 13]);         }     }      //shuffles deck     public void shuffle(){          for(int = 0; < deck.length; i++ ){             int j = randnum.nextint(max);             card c = deck[i];             deck[i] = deck[j];             deck[j] = c;         }     }      //returns individual card in deck     public card getcard(int index){         return deck[index];     }      //returns rankint deck object @ given index value     public int getrankint(int index) {         return rankint[index];     }  } 

card

package com.craigreedwilliams.game;  /**  * created reed on 7/10/2015.  */ public class card {     private string rank;     private string suit;     private int rankint;      // todo: remove if never used     private int suitint;      //four argument constructor initializes cards rank , suit (stings , 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 return rank value     public string getrank() {         return rank;     }      //getter method return suit value     public string getsuit() {         return suit;     }      //setter method initialize suit     public int getrankint() {         return rankint;     }      //return string representation of card object     public string tostring() {         return rank + " : " + suit;     } } 

your sql query should this:

 select player,wins yourtable set wins=wins + 1 player=playerid 

the columns examples because don't know how called them ;)

and @ end of each round need query sql-server.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -