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.
Related
I am making a game in which i have randomly spawned objects. I also have a table that has the data of which objects are close to one another, say within a range of 200px - lets call them neighbors. What i want is to generate and assign coordinates to all the available objects so that this relationship is reflected. I want to view the structure of how they are.
I have made a greedy algorithm. Which works very slowly. and gets stuck sometimes. Does anyone have a better approach to this? - the coordinates can be assigned dynamically through trial and error no problem.
Below is the current code classes.
/**
* biggest problem
* */
public void assignInitialCoords( MyObject[] objects )
{
objects[0].setxCoor(rand.nextInt(1000));
objects[0].setyCoor(rand.nextInt(1000));
for(int i=0; i<objects.length; i++ )
{
ArrayList<MyObject> neighs = objects[i].getNeighbours();
System.out.println("Assigning " + objects[i].getId() + "'s coors");
setNonNeighborCoords(objects, i);
setNeighborCoordinates(objects, i, neighs);
System.out.println(objects[i].getId() + "(" + objects[i].getxCoor() + ", " + objects[i].getyCoor() + ")\n");
}
}
The classes
import java.util.ArrayList;
import java.util.HashMap;
public class MyObject
{
public ArrayList<MyObject> neighbours;
public ArrayList<MyObject> nonNeighbours;
public double fov = 360;
public double sRange = 100, xCoor, yCoor;
boolean isClustered = false;
public String id;
//Cluster[] clusters;
public MyObject()
{
neighbours = new ArrayList<MyObject>();
nonNeighbours = new ArrayList<MyObject>();
}
/**
* Find neighbours for this Object given a relations table
* example: if a MyObject has id A, and neighbor is B, then the key can be either: A_B or B_A
* Both represent the same relation, so we only need to check it once
* */
public void findNeighbours(HashMap<String, Integer> table, MyObject[] objects)
{
for (int i = 0; i < objects.length; i++)
{
String key1 = getId() + "_" + objects[i].getId(), key2 = objects[i].getId() +"_" + getId(), key="";
if(table.get(key1) != null)
{
key = key1;
if(table.get(key) <= getsRange())
getNeighbours().add(objects[i]);
}
if(table.get(key2) != null)
{
key = key2;
if(table.get(key) <= getsRange())
getNeighbours().add(objects[i]);
}
}
}
/**
* Check whether a given Object is the neighbour ArrayList of this object
* */
public boolean isInNeighbours( MyObject n )
{
if(neighbours.equals(null)) { return false; }
for(int i=0; i<getNeighbours().size(); i++)
if(getNeighbours().get(i).getId().equals(n.getId())) { return true; }
return false;
}
/**
* Check whether a given Object is the noneighbour ArrayList of this object
* */
public boolean isInNonNeighbours( MyObject n )
{
if(nonNeighbours.equals(null)) { return false; }
for(int i=0; i<getNonNeighbours().size(); i++)
if(getNonNeighbours().get(i).getId().equals(n.getId())) { return true; }
return false;
}
/**
* Check if given MyObject Can be a neighbour to this Object - for rand coord generation
* */
public boolean canBeANeighbour(MyObject n)
{
return distanceTo(n) <= sRange;
}
// return Euclidean distance between this and p
public double distanceTo(MyObject p) {
double dx = this.xCoor - p.xCoor;
double dy = this.yCoor - p.yCoor;
return Math.sqrt(dx*dx + dy*dy);
}
//Setters And Getters
public ArrayList<MyObject> getNeighbours(){ return neighbours; }
public void setNeighbours(ArrayList<MyObject> neighbours)
{
this.neighbours = neighbours;
}
public double getFov()
{
return fov;
}
public void setFov(double fov)
{
this.fov = fov;
}
public double getsRange()
{
return sRange;
}
public void setsRange(double sRange)
{
this.sRange = sRange;
}
public double getxCoor()
{
return xCoor;
}
public void setxCoor(double xCoor)
{
this.xCoor = xCoor;
}
public double getyCoor()
{
return yCoor;
}
public void setyCoor(double yCoor)
{
this.yCoor = yCoor;
}
public boolean isClustered()
{
return isClustered;
}
public void setClustered(boolean isClustered)
{
this.isClustered = isClustered;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public ArrayList<MyObject> getNonNeighbours()
{
return nonNeighbours;
}
public void setNonNeighbours(ArrayList<MyObject> nonNeighbours)
{
this.nonNeighbours = nonNeighbours;
}
}
//The sample test:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
public class SampleField
{
Random rand = new Random();
public int range = 100;
HashMap<String, Integer> table = new HashMap<String, Integer>();
String[] nodeIds = {"A", "B", "C", "D", "E", "F"};
public MyObject[] objects = new MyObject[nodeIds.length];
public static void main(String[] args)
{
SampleField test = new SampleField();
for(MyObject n: test.objects)
{
n.findNeighbours(test.table, test.objects);
}
test.populateNonNeighbours(test.objects);
System.out.println(test.table);
test.printRelationsTable( test.objects );
test.assignInitialCoords(test.objects);
System.out.println(test.table);
test.printRelationsTable( test.objects );
}
public SampleField()
{
initialiseNodes();
generateTestTable(objects);
}
/**
* biggest problem
* */
public void assignInitialCoords( MyObject[] objects )
{
objects[0].setxCoor(rand.nextInt(1000));
objects[0].setyCoor(rand.nextInt(1000));
for(int i=0; i<objects.length; i++ )
{
ArrayList<MyObject> neighs = objects[i].getNeighbours();
System.out.println("Assigning " + objects[i].getId() + "'s coors");
setNonNeighborCoords(objects, i);
setNeighborCoordinates(objects, i, neighs);
System.out.println(objects[i].getId() + "(" + objects[i].getxCoor() + ", " + objects[i].getyCoor() + ")\n");
}
}
/**
* if this object has neighbours, try to set their coordinates so that they do not conflict
*
* #param objects
* #param i
* #param neighs
*/
private void setNeighborCoordinates(MyObject[] objects, int i, ArrayList<MyObject> neighs)
{
//it should have at least one neighbour
if(neighs != null )
for( int j=0; j<neighs.size(); j++ )
{
//Initial assignment to the first neighbor
neighs.get(j).setxCoor(rand.nextInt() + objects[i].getsRange() );
neighs.get(j).setyCoor(rand.nextInt() + objects[i].getsRange() );
//If not a neighbor keep generating coordinates until it keeps being a neighbor.
while( !objects[i].canBeANeighbour(neighs.get(j)) )
{
//go deeper? - later
neighs.get(j).setxCoor(rand.nextInt(1000) - shootRange() - 5 );
neighs.get(j).setyCoor(rand.nextInt(1000) - shootRange() - 5 );
}
}
}
/**
* try to set the coordinates of each object here
* #param objects
* #param i
*/
private void setNonNeighborCoords(MyObject[] objects, int i)
{
for(MyObject n : objects[i].getNonNeighbours())
{
n.setxCoor(rand.nextInt() + shootRange() - 5);
n.setyCoor(rand.nextInt() + shootRange() - 5);
//Make sure non neighbors remain non neighbors
while(objects[i].canBeANeighbour(n))
{
n.setxCoor(rand.nextInt() + shootRange() - 5 );
n.setyCoor(rand.nextInt() + shootRange() - 5 );
}
}
}
/* populate nonNeighbours */
public void populateNonNeighbours(MyObject[] objects)
{
for(int i=0; i<objects.length; i++)
{
for(int j=0; j<objects.length; j++ )
{
if( (objects[i].getId() != objects[j].getId()) && !objects[i].isInNeighbours(objects[j]) )
{
objects[i].getNonNeighbours().add(objects[j]);
}
}
}
}
/* Show each object and its neighbors/nonneighbors - just for output */
public void printRelationsTable( MyObject[] objects )
{
for(int i=0; i<objects.length; i++ )
{
System.out.print("MyObject " + objects[i].getId() + "'s neighbours: ");
for(int j=0; j<objects[i].getNeighbours().size(); j++)
{
System.out.print(objects[i].getNeighbours().get(j).getId() + " ");
}
System.out.println();
System.out.print("\t\t" +objects[i].getId()+ "' : ");
for(int j=0; j<objects[i].getNonNeighbours().size(); j++)
{
System.out.print(objects[i].getNonNeighbours().get(j).getId() + " ");
}
System.out.println();
}
}
/* Initialise Objects here - give basic information */
public void initialiseNodes()
{
for(int i=0; i<nodeIds.length; i++)
{
MyObject n = new MyObject();
n.setId(nodeIds[i]);
n.setsRange(shootRange());
objects[i] = n;
}
}
/* Generate a list of neighbors for testing */
public void generateTestTable(MyObject[] objects)
{
for(int i=0; i<objects.length; i++)
{
/* Get two objects' ids and make them neighbors - ids must be unique */
String firstId = objects[rand.nextInt(objects.length)].getId();
String secondId = objects[rand.nextInt(objects.length)].getId();
while( firstId.equals(secondId) || table.containsKey(firstId + "_" + secondId) || table.containsKey(secondId + "_" + firstId) )
{
firstId = objects[rand.nextInt(objects.length)].getId();
secondId = objects[rand.nextInt(objects.length)].getId();
}
table.put(firstId + "_" + secondId, shootRange());
}
}
/* Range within which they are neighbors */
public int shootRange()
{
return range;
}
public void setRange(int range)
{
this.range = range;
}
}
If you only compare distances (and if you are talking about neighbours, it seems so), then you don't need to count them at all. Instead of
range = sqrt(sqr(a.x-b.x)+sqr(a.y-b.y))
if (range >d)...
use
sqrange(a,b) = sqr(a.x-b.x)+sqr(a.y-b.y)
if (range> d_sqr) ...
That means, you don't use ranges, but their squares. That quickens the comparisons about 50 times (for double). So, you can use much more easy structures.
I have used an existing genetic algorithm from
here
and reworked it I but don't know what I'm doing wrong
This is the error that I get
Exception in thread "main" java.lang.NullPointerException at
simpleGa.Algorithm.crossover(Algorithm.java:69) at
simpleGa.Algorithm.evolvePopulation(Algorithm.java:34) at
simpleGa.GAprisonerdilemma.main(GAprisonerdilemma.java:41)
I can't figure out exactly where the mistake is. Read a lot about NullPointerException but couldn't figure it out
package simpleGa;
public class Population {
public static Individual[] individuals;
/*
* Constructors
*/
// Create a population
public Population(int populationSize, boolean initialise) {
individuals = new Individual[populationSize];
// Initialise population
if (initialise) {
// Loop and create individuals
for (int i = 0; i < size(); i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
for(int i=0;i<size();i++)
{
if(i%2==1){Individual individual1=individuals[i-1];
Individual individual2=individuals[i];
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+1;
individuals[i].fitness=individual2.fitness+1;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+2;
individuals[i].fitness=individual2.fitness+2;
}
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+3;
individuals[i].fitness=individual2.fitness+0;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+0;
individuals[i].fitness=individual2.fitness+3;
}
}}}
}
/* Getters */
public Individual getIndividual(int index) {
return individuals[index];
}
public Individual getFittest() {
Individual fittest = individuals[0];
// Loop through individuals to find fittest
for (int i = 1; i < size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
/* Public methods */
// Get population size
public int size() {
return individuals.length;
}
// Save individual
public void saveIndividual(int index, Individual indiv) {
individuals[index] = indiv;
}
}
package simpleGa;
public class Individual {
static int defaultGeneLength = 1000;
private long[] genes =new long [defaultGeneLength];
// Cache
public static int fitness = 0;
// Create a random individual
public void generateIndividual() {
for (int i = 0; i < size(); i++) {
long gene = Math.round(Math.random());
genes[i] = gene;
}
}
/* Getters and setters */
// Use this if you want to create individuals with different gene lengths
public static void setDefaultGeneLength(int length) {
defaultGeneLength = length;
}
public long getGene(int i) {
return genes[i];
}
public void setGene(int index, long value) {
genes[index] = value;
fitness = 0;
}
/* Public methods */
public int size() {
return genes.length;
}
public static int getFitness() {
return fitness;
}
public void setFitness(int i) {
fitness=i;
}
#Override
public String toString() {
String geneString = "";
for (int i = 0; i < size(); i++) {
geneString += getGene(i);
}
return geneString;
}
}
package simpleGa;
public class Algorithm {
/* GA parameters */
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.015;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
/* Public methods */
// Evolve a population
public static Population evolvePopulation(Population pop) {
Population newPopulation = new Population(pop.size(), false);
// Keep our best individual
if (elitism) {
newPopulation.saveIndividual(0, pop.getFittest());
}
// Crossover population
int elitismOffset;
if (elitism) {
elitismOffset = 1;
} else {
elitismOffset = 0;
}
// Loop over the population size and create new individuals with
// crossover
for (int i = elitismOffset; i < pop.size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.saveIndividual(i, newIndiv);
}
// Mutate population
for (int i = elitismOffset; i < newPopulation.size(); i++) {
mutate(newPopulation.getIndividual(i));
}
for(int i=0;i<pop.size();i++)
{for(int j=0;j<pop.getIndividual(i).size();j++)
{if(i%2==1){Individual individual1=Population.individuals[i-1];
Individual individual2=Population.individuals[i];
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+1;
Population.individuals[i].fitness=individual2.fitness+1;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+2;
Population.individuals[i].fitness=individual2.fitness+2;
}
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+3;
Population.individuals[i].fitness=individual2.fitness+0;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+0;
Population.individuals[i].fitness=individual2.fitness+3;
} }}}``
return newPopulation;
}
// Crossover individuals
private static Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
// Loop through genes
for (int i = 0; i < indiv1.size(); i++) {
// Crossover
if (Math.random() <= uniformRate) {
newSol.setGene(i, indiv1.getGene(i));
} else {
newSol.setGene(i, indiv2.getGene(i));
}
}
return newSol;
}
// Mutate an individual
private static void mutate(Individual indiv) {
// Loop through genes
for (int i = 0; i < indiv.size(); i++) {
if (Math.random() <= mutationRate) {
// Create random gene
long gene = Math.round(Math.random());
indiv.setGene(i, gene);
}
}
}
// Select individuals for crossover
private static Individual tournamentSelection(Population pop) {
// Create a tournament population
Population tournament = new Population(tournamentSize, false);
// For each place in the tournament get a random individual
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.size());
tournament.saveIndividual(i, pop.getIndividual(randomId));
}
// Get the fittest
Individual fittest = tournament.getFittest();
return fittest;
}
package simpleGa;
public class FitnessCalc {
/* Public methods */
// Set a candidate solution as a byte array
// To make it easier we can use this method to set our candidate solution
// with string of 0s and 1s
// Calculate inidividuals fittness by comparing it to our candidate solution
static int getFitness(Individual individual) {
int fitness = 0;
// Loop through our individuals genes and compare them to our cadidates
fitness=Individual.fitness;
return fitness;
}
}
// Get optimum fitness
}
package simpleGa;
import java.util.Scanner;
public class GAprisonerdilemma {
public static void main(String[] args) {
// Set a candidate solution
Scanner keyboard = new Scanner(System.in);
System.out.println("Input number of games!");
int k = keyboard.nextInt();
Individual.setDefaultGeneLength(k);
// Create an initial population
System.out.println("Input number of individuals in the population!");
int p = keyboard.nextInt();
Population myPop = new Population(p, true);
System.out.println("Input acceptable number of generations!");
int l = keyboard.nextInt();
// Evolve our population until we reach an optimum solution
int generationCount = 0;
int j=l+1;
System.out.println("Input requiered fitness value !");
int f = keyboard.nextInt();
int h=0;
// Evolve our population until we reach an optimum solution
for(int i=0;i<j;i++)
{
if(i==0){}
else{
if(myPop.getFittest().getFitness()>=f){if(h==0){h++;}
else{ System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println( "Fitness(Points): " + myPop.getFittest().getFitness());
break;}
}else {myPop = Algorithm.evolvePopulation(myPop);
generationCount++;
System.out.println("Generation: " + generationCount + " Fittest: " + myPop.getFittest().getFitness());
}
if(i==j-1){ if(myPop.getFittest().getFitness()>=f)System.out.println("Solution found !");
else System.out.println("Solution not found closest solution is!");
System.out.println("Generation: " + generationCount);
System.out.println( " Fitness(Points): " + myPop.getFittest().getFitness());}
}
}
System.out.println("0 for betrays in that turn 1 for cooperates!");
System.out.println("Turns:");
System.out.println(myPop.getFittest());
}
}
First, thanks for reading this, I'm going to start by posting all code relevant to the program which you can skim or completely skip over for now.
Try to ignore all my sarcastic comments throughout the code btw they aren't directed at stack overflow :P
BlackJack file:
import java.util.Scanner;
import java.util.InputMismatchException;
public class BlackJack { //i should probably put a betting thing somewhere.....
//also should probably add a thing that tells them one of the dealers cards
//should also put something that stops 2 players from having the same name
static Scanner input = new Scanner(System.in); //honestly have no idea if i can put this here but it seems to work. keyword; seems
//good lucking counting cards with all this shuffling lol
public void absolutelyNothing() { //maybe put a betting method here instead of a method that does nothing???
//Do NOT Delete This Method!
}
public static void displayHands(Hand[] hands, String[] playerNames, int players) {
for (int i = 1; i < players; i++) {
display(hands, playerNames, i);
}
displayDealer(hands);
}
public static void display(Hand[] hands, String[] playerNames, int i) {
System.out.println(playerNames[i] + " has " + hands[i]);
}
public static void displayDealer(Hand[] hands) {
System.out.println("Dealer has " + hands[0].dealerDisplay());
}
public static boolean win(Hand[] hands, int i) {
int value = worth(hands[i]);
int dealer = worth(hands[0]);
if (value == -1) {
return false;
}
if (value > dealer) {
return true;
}
return false;
}
public static void winners(Hand[] hands, String[] playerNames) {
for (int i = 1; i < hands.length; i++) {
if (win(hands, i) == true) {
System.out.println(playerNames[i] + " beat the dealer");
}
else {
System.out.println(playerNames[i] + " lost to the dealer");
}
}
}
public static int worth(Hand hand) {
int sum = 0;
int aces = 0;
for (int i = 0; i < hand.howManyCards(); i++) {
Card card = hand.getCard(i);
int value;
if (card.getNumber() == -10) {
aces++;
value = 11;
}
else {
value = card.getNumber();
}
sum+= value;
}
for (int i = 0; aces > i; i++) {
if (sum >= 22) {
sum = sum - 10;
}
}
if (sum >= 22) {
return -1;
}
return sum;
}
public static void dealerTurn(Deck deck, Hand[] hands) {
int worth = worth(hands[0]);
while (worth < 16) {
dealCard(deck, hands, 0);
}
}
public static void playTurn(Deck deck, Hand[] hands, int i, String[] playerNames) {
// System.out.println(playerNames[i] + " hit?" + " Your hand is worth " + worth(hands[i]) );
boolean hit;
displayHands(hands, playerNames, hands.length);
while (true) {
if (worth(hands[i]) == -1) {
System.out.println("Bust");
break;
}
System.out.println(playerNames[i] + " hit?" + " Your hand is worth " + worth(hands[i]) );
try {
hit = input.nextBoolean();
}
catch (InputMismatchException exception) {
System.out.println("Please enter \"true\" or \"false\"");
continue; //pretty sure this continue is causing the glitch where if you don't enter a boolean it goes insane
}
if (hit == true) {
dealCard(deck, hands, i);
}
else {
break;
}
}
}
public static void everyoneGo(Deck deck, Hand[] hands, int players, String[] playerNames) {
for (int j = 1; j < players + 1; j++) { //players go
playTurn(deck, hands, j, playerNames);
}
dealerTurn(deck, hands);
}
public static Deck newHand(Deck deck) {
Deck newDeck = new Deck();
return newDeck;
}
public static void dealCard(Deck deck, Hand[] hands, int i) {
deck.shuffleDeck();
//goodluck counting cards
hands[i].addCard(deck.getCard(0));
deck.removeCard(0);
}
public static void giveNextCard(Hand[] hands, Deck deck, int i) {
hands[i].addCard(deck.getCard(0));
deck.removeCard(0);
}
public static Hand[] firstTwoCards(int players, String[] playerNames, Deck deck) { //gives dealer cards first an I'm too lazy to fix
deck.shuffleDeck();
//seriously good luck
Hand[] hands = new Hand[players + 1]; //dealer is hands[0]
for (int i = 0; i < players + 1; i++) {
hands[i] = new Hand(playerNames[i]);
}
for (int j = 0; j < 2; j++) {
for (int i = 0; i < players + 1; i++) {
giveNextCard(hands, deck, i);
}
}
return hands;
}
public static String[] getNames(int players) {
System.out.println("What are the names of the players?");
String[] playerNames = new String[players + 1];
playerNames[0] = "Dealer";
for (int i = 1; i < players + 1; i++) {
playerNames[i] = input.next(); //something with this line the last time you use it
}
return playerNames;
}
public static int peoplePlaying() {
System.out.println("How many people are playing?");
int players = input.nextInt();
return players;
}
public static void main(String[] args) {
int players = peoplePlaying();
String[] playerNames = getNames(players);
Deck deck = new Deck();
Hand[] hands = firstTwoCards(players, playerNames, deck);
everyoneGo(deck, hands, players, playerNames);
winners(hands, playerNames);
}
}
//if you're smart you would have realized all this shuffling has absolutely no effect on counting cards lol now figure out why
Hand File:
public class Hand extends CardList {
public Hand(String label) {
super(label);
}
public void display() {
System.out.println(getLabel() + ": ");
for (int i = 0; i < size(); i++) {
System.out.println(getCard(i));
}
System.out.println();
}
}
Deck File:
public class Deck extends CardList {
public Deck(String label) {
super(label);
for (int suit = 0; suit <= 3; suit++) {
for (int rank = 1; rank <= 13; rank++) {
addCard(new Card(rank, suit));
}
}
}
}
Cardlist File:
import java.util.ArrayList;
import java.util.Random;
public class CardList {
public String name;
public ArrayList<Card> cards;
public CardList(String name) {
this.name = name;
this.cards = new ArrayList<Card>();
}
public String toString() {
String s = "";
for (int i = 0; i < cards.size(); i++) {
s = s + cards.get(i) + ", ";
}
return s;
}
public String dealerDisplay() {
return cards.get(0).toString();
}
public String getName() {
return name;
}
public Card getCard(int i) {
return cards.get(i);
}
public int howManyCards() {
return cards.size();
}
public void addCard(Card card) {
cards.add(card);
}
public void removeCard(int i) {
cards.remove(i);
}
public void swapCards(int i, int j) {
Card wait = cards.get(i);
cards.set(i, cards.get(j));
cards.set(j, wait);
}
public void shuffleDeck() {
for (int k = 0; k < 10; k++) { //not sure how well the algorithm works but if you do it 10 times it shouldn't matter how bad it is
for (int i = 0; i < howManyCards(); i++) {
int j = (int) (Math.random() * howManyCards());
swapCards(i, j);
}
}
}
}
and finally the card object:
public class Card {
int number;
int suit;
public static final String[] NUMBERS = {null, null, "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
public static final String[] SUITS = {"Diamonds", "Clubs", "Spades", "Hearts"};
public Card(int number, int suit) {
this.number = number;
this.suit = suit;
}
#Override
public String toString() {
return NUMBERS[number] + " of " + SUITS[suit];
}
public int getNumber() {
if (number == 14) { //used to tell if its an ace in blackjack file
return -10;
}
if (number < 11) {
return number;
}
else {
return 10;
}
}
}
Alright so hopefully you didn't kill yourself by attempting to read all of that and I realize my code style/organization could use some work.
Anyways their are a few things that are very weird with the program that I can't seem to figure out. Sometimes the program will run fine and you can play a full game with lots of players but other times it throws a bunch of exceptions.
basically if you bust (go over 21) the program throws this 100% of the time:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at CardList.getCard(CardList.java:31)
at BlackJack.dealCard(BlackJack.java:151)
at BlackJack.dealerTurn(BlackJack.java:93)
at BlackJack.everyoneGo(BlackJack.java:138)
at BlackJack.main(BlackJack.java:209)
btw if someone could explain what it means by exceptions at lines that don't exist such as 653 (the first message) that would be very helpful.
It also throws the same exception some of the time even if you don't bust which I'm assuming is the dealer busting as the dealer plays automatically obeying the regular casino rules for dealers.
If anyone can figure it out it would be greatly appreciated, thanks!
I am new to Java programming. I developed a Pizza class that takes for parameters and outputs the description and cost. I developed a PizzaOrderArray class that stores the pizza orders in an array. I have a class containing the main method also.
When I tried to print the values of the orders, nothing prints yet debugging shows that the proper methods and loops were entered.
What am I doing incorrect? I have invested many hours and am still very confused. Any suggestions, please? Thank you! I appreciate it.
Pizza.java
import java.text.NumberFormat;
import java.util.Locale;
public class Pizza {
public Pizza(String size, int numCheeseTop, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
setNumCheese(numCheeseTop);
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_pep = 0;
setNumHam(numHamTop);
pizza_cheese = 0;
}
public Pizza(String size) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza() {
pizza_size = "small";
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza(Pizza copyPizza) {
pizza_size = copyPizza.getPizzaSize();
pizza_cheese = copyPizza.getNumCheese();
pizza_pep = copyPizza.getNumPep();
pizza_ham = copyPizza.getNumHam();
}
//Setters
public boolean setPizzaSize(String size) {
if (size.equalsIgnoreCase("small") || (size.equalsIgnoreCase("medium") || (size.equalsIgnoreCase("large")))) {
pizza_size = size.toLowerCase();
return true;
}
return false;
}
public void setNumCheese(int numCheeseTop) {
pizza_cheese = numCheeseTop;
}
public void setNumPep(int numPepTop) {
pizza_pep = numPepTop;
}
public void setNumHam(int numHamTop) {
pizza_ham = numHamTop;
}
//End of setters
//Getters
public String getPizzaSize() {
return pizza_size;
}
public int getNumCheese() {
return pizza_cheese;
}
public int getNumPep() {
return pizza_pep;
}
public int getNumHam() {
return pizza_ham;
}
//End of getters
public double calcCost() {
if (pizza_size.toLowerCase() == "small") {
return 10 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "medium") {
return 12 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "large") {
return 14 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() != "small" && pizza_size.toLowerCase() != "medium"
&& pizza_size.toLowerCase() != "large") {
System.out.println("Invalid pizza size");
return 0;
}
return 0;
}
public String getDescription() {
return pizza_size + " pizza with " + pizza_cheese + " cheese toppings " + pizza_pep + " pepperoni toppings and "
+ pizza_ham + " ham toppings "; //+ " which is " + money.format(pizza2.calcCost());
}
//private String pizza_size;
//private int pizza_cheese, pizza_pep, pizza_ham;
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
} //End of Pizza class
PizzaOrderArray.java
import static java.lang.System.out;
public class PizzaOrderArray {
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
//private String pizza_size;
//private int pizza_cheese; pizza_pep; pizza_ham;
private Pizza[] pizza;
private int index = 0;
public PizzaOrderArray() {
System.out.println("PizzaOrderArray()");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(int i) {
System.out.println("PizzaOrderArray(int i)");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(PizzaOrderArray poa) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa)");
pizza = new Pizza[poa.index];
index = poa.index;
for (int i = 0; i < poa.index; i++) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa) for loop");
pizza[i] = new Pizza(poa.pizza[i]);
}
}
public void setPizza(int index1, Pizza newpizza) {
System.out.println("Inside of setPizza");
pizza[index1] = new Pizza(newpizza);
}
public String getPizzaSize() {
System.out.println("Inside of getPizzaSize");
return pizza_size;
}
public int getNumCheese() {
System.out.println("Inside of getNumCheese");
return pizza_cheese;
}
public int getNumPep() {
System.out.println("Inside of getNumPep");
return pizza_pep;
}
public int getNumHam() {
System.out.println("Inside of getNumHam");
return pizza_ham;
}
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for (int i = 0; i < indexUsed; i++) {
s = (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
return s;
}
public double calcTotal() {
double r = 0.0;
System.out.println("Inside of calcTotal");
for (int i = 0; i < index; i++) {
System.out.println("Inside of calcTotal for loop");
r = r + pizza[i].calcCost();
}
return r;
}
public boolean equals(PizzaOrderArray orderarray) {
boolean r = false;
System.out.println("Inside of equals");
if (orderarray.pizza.length != pizza.length) {
System.out.println("Inside of equals if");
return r;
}
for (int i = 0; i < orderarray.pizza.length; i++) {
if (pizza[i].equals(orderarray.pizza[i])) {
System.out.println("Inside of equals for-if");
r = true;
} else {
System.out.println("Inside of equals for-else");
return false;
}
}
System.out.println("Return of equals");
return r;
}
} //End of PizzaOrderArray class
V4_Project_15_page_418.java
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.Arrays;
public class V4_Project_15_page_418 {
public static void main(String args[]) {
//Order1
PizzaOrderArray order1 = new PizzaOrderArray();
Pizza pizzaone = new Pizza("Medium", 0, 0, 0);
Pizza pizzatwo = new Pizza("Small", 1, 0, 0);
order1.setPizza(0, pizzaone);
System.out.println("Order 1: ");
System.out.println(order1.toString());
System.out.println(order1);
System.out.println();
//Order2
Pizza pizzathree = new Pizza(pizzatwo);
PizzaOrderArray order2 = new PizzaOrderArray(2);
order2.setPizza(0, pizzaone);
order2.setPizza(0, pizzatwo);
System.out.println("Order 2: ");
System.out.println(order2.toString());
System.out.println(order2);
System.out.println();
//Order3
PizzaOrderArray order3 = new PizzaOrderArray(1);
order3.setPizza(0, pizzaone);
order3.setPizza(0, pizzatwo);
System.out.println("Order 3: ");
System.out.println(order3.toString());
System.out.println(order3);
System.out.println();
//Order4
PizzaOrderArray order4 = new PizzaOrderArray(order3);
System.out.println("Order 4: ");
System.out.println(order4.toString());
System.out.println(order4);
//TEST THE PROGRAM
System.out.println("TEST: The total for order 4 is: " + order4.calcTotal());
System.out.println();
//Order5
PizzaOrderArray order5 = new PizzaOrderArray(order1);
System.out.println("Order5: ");
System.out.println(order5);
System.out.println();
}//End of main class
}//End of V4_Project_15_page_418 class
Output:
PizzaOrderArray()
Inside of setPizza
Order 1:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 2:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 3:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order 4:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
Inside of calcTotal
Inside of calcTotal for loop
Invalid pizza size
TEST: The total for order 4 is: 0.0
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order5:
Inside of toString
Inside of toString for loop
Take a close look at the condition in this for loop, it isn't going to ever print anything since the condition is never true since i is never less than indexUsed which is 0.
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
return s;
}
Something also need pay attention to:
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
means:
for(int i = 0; i < indexUsed; i++) {
s= (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
So this is System.out.println just misleading you, you are never "inside of" the for loop.
I think it's better to always use the braces '{}' with for/while loop.
The snippet
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString()); is wrong, your for loop is never executed since indexUsed is 0
In your toString method, the for loop condition never becomes true (before the first iteration itself, 0<0 becomes false & loop terminates without executing once) so the loop never executes.
You can try changing the for loop statement to:
for(int i = 0; i < index; i++)
I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}