How can I assign the driver to UNO DiscardPile.java? - java

I'm creating an UNO project and am a bit confused about how to assign the drivers to my DiscardPile class.
Thank you in advance for any answers you may give.
Sincerely,
Jayda M
I've asked my fellow students for assistance and have scoured the internet for anything that could be helpful with no luck. My professor isn't helpful at all haha
This is the full code for the Driver.java file. If you need me to give you any of the others I have no problem doing so.
package unoGame;
import java.util.Random;
//import java.util.Collections;
public class Driver {
public static unoDeck theDeck = new unoDeck();
public static PlayerHand[] thePlayers;
public static DiscardPile dp = new DiscardPile();
public static int nextPlayer;
public static Random getRandom = new Random();
public static void main(String[] args) {
// TODO Auto-generated method stub
thePlayers = new PlayerHand[3];
thePlayers[0] = new PlayerHand("name 1");
thePlayers[1] = new PlayerHand("name 2");
thePlayers[2] = new PlayerHand("name 3");
theDeck.shuffle();
System.out.println("Here is the Deck: " + theDeck);
System.out.println(" Welcome to UNO! ");
if (dp.isEmpty()) {
System.out.println(" Discard is Empty ");
}
else {
System.out.println(" Not Empty ");
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < thePlayers.length; j++) {
thePlayers[j].addCard(theDeck.deal());
}
}
nextPlayer = 0;
showPlayers();
dp.addCard(theDeck.deal());
while (checkForWin() == false) {
findNextPlayer();
if (theDeck.isEmpty()) {
theDeck.replenish(dp.clear());
}
playerTurn();
}
System.out.println(thePlayers[nextPlayer], getName() + " Wins!")
}
public static void showPlayers() {
for (PlayerHand p : thePlayers)
System.out.println(p);
}
public static boolean checkForWin() {
if (p.isWin()) {
win = true;
}
return win;
}
public static void findNextPlayer() {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
if(dp.getTopCard().getValue()=="SK") {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
}
if(dp.getTopCard().getValue() == "D2") {
for(int i = 0; i <= 1; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if(dp.getTopCard().getValue() == "W4") {
for(int i = 0; i <= 3; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if(dp.getTopCard().getValue() == "RV") {
for(int i = 0; i < thePlayers.length / 2; i++) {
PlayerHand rev = thePlayers[i];
thePlayers[i] = thePlayers[thePlayers.length - i -1];
rev = thePlayers[thePlayers.length - i -1];
if(nextPlayer == 0) {
nextPlayer = 0;
}
if(nextPlayer == 2) {
nextPlayer = 1;
}
}
nextPlayer++;
}
}
public static void playerTurn() {
if (thePlayers[nextPlayer].hasMatch(dp.getTopCard())) {
System.out.println(thePlayers[nextPlayer].getName() + " has a match!");
unoCard c = thePlayers[nextPlayer].playCard(dp.getTopCard());
dp.addCard(c);
if(c.getValue().equals("W")) {
c.setColor(theDeck.newColor());
}
if(c.getValue().equals("W4")) {
c.setColor(theDeck.newColor());
}
System.out.println(thePlayers[nextPlayer].getName() + " played a: " dp.getTopCard());
System.out.println(thePlayers[nextPlayer]);
}
else {
unoCard c = theDeck.deal();
thePlayers[nextPlayer]c.addCard(c);
System.out.println(thePlayers[nextPlayer].getName() + " drew a: " + c);
}
}
}
There are errors are on these lines of code: 46, 50, 57, 58, 60, 106 and 111. Most of them are saying they're undefined, and I'm unsure of where to do so amongst my files. I'm expecting the Driver to run the game as a whole, so because it's gone wack I can't run the build properly. If you need more information to work with, I'll gladly give it to you!
EDIT:
The lines and/or words where the errors are taking place have asterisks around them
The error descriptions with their corresponding lines
The printed console error after running Driver. Hopefully this works for the Reproducible Example required :)

Here is your Driver class with compilation problems fixed. I suggest you compare it with your current code in order to see what I changed.
I also needed to add method replenish() in class unoDeck because it didn't exist and is called from class Driver. Right now that method does nothing. As I said, I only added it in order to fix the compilation error.
package unoGame;
import java.util.Random;
public class Driver {
public static unoDeck theDeck = new unoDeck();
public static PlayerHand[] thePlayers;
public static DiscardPile dp = new DiscardPile();
public static int nextPlayer;
public static Random getRandom = new Random();
public static void main(String[] args) {
thePlayers = new PlayerHand[3];
thePlayers[0] = new PlayerHand("name 1");
thePlayers[1] = new PlayerHand("name 2");
thePlayers[2] = new PlayerHand("name 3");
theDeck.shuffle();
System.out.println("Here is the Deck: " + theDeck);
System.out.println(" Welcome to UNO! ");
if (dp.isEmpty()) {
System.out.println(" Discard is Empty ");
}
else {
System.out.println(" Not Empty ");
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < thePlayers.length; j++) {
thePlayers[j].addCard(theDeck.deal());
}
}
nextPlayer = 0;
showPlayers();
dp.addCard(theDeck.deal());
while (checkForWin() == false) {
findNextPlayer();
if (theDeck.isEmpty()) {
theDeck.replenish(dp.clear());
}
playerTurn();
}
System.out.println(thePlayers[nextPlayer].getName() + " Wins!");
}
public static void showPlayers() {
for (PlayerHand p : thePlayers)
System.out.println(p);
}
public static boolean checkForWin() {
boolean win = false;
if (thePlayers[nextPlayer].isWin()) {
win = true;
}
return win;
}
public static void findNextPlayer() {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
if (dp.getTopCard().getValue() == "SK") {
nextPlayer++;
nextPlayer = nextPlayer % thePlayers.length;
}
if (dp.getTopCard().getValue() == "D2") {
for (int i = 0; i <= 1; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if (dp.getTopCard().getValue() == "W4") {
for (int i = 0; i <= 3; i++) {
thePlayers[nextPlayer].addCard(theDeck.deal());
}
}
if (dp.getTopCard().getValue() == "RV") {
for (int i = 0; i < thePlayers.length / 2; i++) {
PlayerHand rev = thePlayers[i];
thePlayers[i] = thePlayers[thePlayers.length - i - 1];
rev = thePlayers[thePlayers.length - i - 1];
if (nextPlayer == 0) {
nextPlayer = 0;
}
if (nextPlayer == 2) {
nextPlayer = 1;
}
}
nextPlayer++;
}
}
public static void playerTurn() {
if (thePlayers[nextPlayer].hasMatch(dp.getTopCard())) {
System.out.println(thePlayers[nextPlayer].getName() + " has a match!");
unoCard c = thePlayers[nextPlayer].playCard(dp.getTopCard());
dp.addCard(c);
if(c.getValue().equals("W")) {
c.setColor(theDeck.newColor());
}
if(c.getValue().equals("W4")) {
c.setColor(theDeck.newColor());
}
System.out.println(thePlayers[nextPlayer].getName() + " played a: " + dp.getTopCard());
System.out.println(thePlayers[nextPlayer]);
}
else {
unoCard c = theDeck.deal();
thePlayers[nextPlayer].addCard(c);
System.out.println(thePlayers[nextPlayer].getName() + " drew a: " + c);
}
}
}

Related

ArrayList of ArrayLists is overridden when setting values of a second one

I'm trying to make a battleship game, and this is the part where the players set their boards. When the second player to set the board makes theirs, the first player's board becomes the same as the second player's (when playing the game guessing the locations of that board are misses though, but that's another problem that will hopefully be fixed once this is). For example if I set the first player's ships as being at A1 A2 A3, B1 B2 B3, and C1 C2 C3, then set the second player's ships as D1 D2 D3, E1 E2 E3, and F1 F2 F3, when both lists of ships are printed out I get D1 D2 D3, E1 E2 E3, and F1 F2 F3 for both ships. I've found other questions on here with the same problem, but they always had the problem because they didn't make new lists every time, which I do (at least I'm pretty sure I do), so I can't find where my problem is. Here is the entire main game class, the GetShipLocations, SetShipLocations, and PlayersMakeTheirBoards, functions are what are giving me problems.
import java.util.*;
import java.lang.*;
public class MainGame {
InputReader read = new InputReader();
Grid p1Board = new Grid();
Grid p2Board = new Grid();
Grid p1ShipsBoard = new Grid();
Grid p2ShipsBoard = new Grid();
ArrayList<Ship> p1Ships = new ArrayList<Ship>();
ArrayList<Ship> p2Ships = new ArrayList<Ship>();
String activePlayer = "P1";
public void SetUp() {
p1Board.PrepPrintGrid();
p2Board.PrepPrintGrid();
Ship ship1 = new Ship();
Ship ship2 = new Ship();
Ship ship3 = new Ship();
p1Ships.add(ship1);
p1Ships.add(ship2);
p1Ships.add(ship3);
p2Ships.add(ship1);
p2Ships.add(ship2);
p2Ships.add(ship3);
}
public void GameIntro() {
System.out.println("Welcome to battleship!");
String rulesOption = read.getUserInput("Do you need to see the rules?");
if(rulesOption.equals("Yes") || rulesOption.equals("yes"))
{
System.out.println("Put rules here");
}
System.out.println("Randomly determining which player goes first");
int random = (int) (Math.random() * 2);
if(random == 1)
{
activePlayer = "P2";
}
System.out.println(activePlayer + " starts!");
}
public ArrayList<ArrayList<String>> GetShipLocations(Grid board) {
ArrayList<ArrayList<String>> ships = new ArrayList<ArrayList<String>>();
ArrayList<String> ship1 = new ArrayList<String>();
ArrayList<String> ship2 = new ArrayList<String>();
ArrayList<String> ship3 = new ArrayList<String>();
ships.add(ship1);
ships.add(ship2);
ships.add(ship3);
String[] numbers = {"first", "second", "third"};
board.PrepPrintGrid();
board.PrintGrid();
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
String coordinate = read.getUserInput("Enter the " + numbers[j] + " coordinate of your " + numbers[i] + " ship (3 long):");
ships.get(i).add(coordinate);
board.SetGridDisplay(coordinate, "hit");
board.PrintGrid();
}
}
return ships;
}
public void SetShipLocations(ArrayList<Ship> ship, Grid activeBoard) {
ArrayList<ArrayList<String>> shipLocations = GetShipLocations(activeBoard);
for(int i = 0; i < 3; i++) {
ship.get(i).SetCells(shipLocations.get(i));
}
}
public void PlayersMakeTheirBoards() {
if(activePlayer.equals("P1"))
{
System.out.println("Hand the computer to player one.");
System.out.println("Player one, time to set your board.");
SetShipLocations(p1Ships, p1ShipsBoard);//the effects of this seem to maybe be overriden when the second board is set
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p1Ships.get(i).cells.get(j));
}
}
System.out.println("Hand the computer to player two.");
System.out.println("Player two, time to set your board.");
SetShipLocations(p2Ships, p2ShipsBoard);
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p2Ships.get(i).cells.get(j));
}
}
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p1Ships.get(i).cells.get(j));
}
}
}
else
{
System.out.println("Hand the computer to player two.");
System.out.println("Player two, time to set your board.");
SetShipLocations(p2Ships, p2ShipsBoard);
/*for(int i = 0; i < 100; i++)
{
System.out.println("");
}*/
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p2Ships.get(i).cells.get(j));
}
}
System.out.println("Hand the computer to player one.");
System.out.println("Player one, time to set your board.");
SetShipLocations(p1Ships, p1ShipsBoard);
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p1Ships.get(i).cells.get(j));
}
}
for(int i = 0; i < /*100*/3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.println(p2Ships.get(i).cells.get(j));
}
}
}
}
public void PlayTheGame() {
String guess = new String();
String result = new String();
for(int i = 0; i < 100; i++)
{
System.out.println("");
}
while(!p1Ships.isEmpty() && !p2Ships.isEmpty())
{
if(activePlayer.equals("P1"))
{
//print the grid
p1Board.PrintGrid();
//ask user for their guess
guess = read.getUserInput("Player one, enter your guess:");
for(Ship boat:p2Ships)
{
result = boat.CheckYourself(guess);
if(result.equals("hit"))
{
System.out.println(result + "!");
break;
}
if(result.equals("kill"))
{
System.out.println(result + "!");
p2Ships.remove(boat);
break;
}
}
if(result.equals("miss"))
{
System.out.println(result);
}
p1Board.SetGridDisplay(guess, result);
activePlayer = "P2";
}
else
{
p2Board.PrintGrid();
//ask user for their guess
guess = read.getUserInput("Player two, enter your guess:");
for(Ship boat:p1Ships)
{
result = boat.CheckYourself(guess);
if(result.equals("hit"))
{
System.out.println(result + "!");
break;
}
if(result.equals("kill"))
{
System.out.println(result + "!");
p1Ships.remove(boat);
break;
}
}
if(result.equals("miss"))
{
System.out.println(result);
}
p2Board.SetGridDisplay(guess, result);
activePlayer = "P1";
}
}
}
public void EndTheGame() {
String winner = new String();
if(p1Ships.isEmpty())
{
winner = "Player two";
p2Board.PrintGrid();
}
else
{
winner = "Player one";
p1Board.PrintGrid();
}
System.out.println("The game is over!");
System.out.println(winner + " wins! Congratulations!");
}
public static void main(String[] args) {
MainGame game = new MainGame();
game.SetUp();
game.GameIntro();
game.PlayersMakeTheirBoards();
game.PlayTheGame();
game.EndTheGame();
}
}
and here is the Ship class
import java.util.*;
public class Ship {
ArrayList<String> cells = new ArrayList<String>();
//String name = new String();
public void SetCells(ArrayList<String> locations) {
cells = locations;
}
/*public void SetName(String word) {
name = word;
}*/
public String CheckYourself(String guess) {
if(cells.contains(guess))
{
cells.remove(guess);
if(cells.isEmpty())
{
return "kill";
}
else
{
return "hit";
}
}
return "miss";
}
}
The grid and reader classes are working perfectly so I didn't include them.
(This is all based off the dotcom battleship game in headfirst java)
In your setup function:
public void SetUp() {
p1Board.PrepPrintGrid();
p2Board.PrepPrintGrid();
Ship ship1 = new Ship();
Ship ship2 = new Ship();
Ship ship3 = new Ship();
p1Ships.add(ship1);
p1Ships.add(ship2);
p1Ships.add(ship3);
p2Ships.add(ship1);
p2Ships.add(ship2);
p2Ships.add(ship3);
}
You are adding the same instances of ship1-3 to both p1Ships and p2Ships. So when you change the ships of player 2, the p1Ships ArrayList is still pointing to the same ships as p2Ships, and thus will always be the same.

Need help : Stack in Vector

I'm doing a project for the university, and I need your help, because I don't find my wish in the API documentation.
I have a class named Belote.java (who simulate a card game).
My professor wants to force us to use the class Stack in a Vector (can't use another class sorry :/ )
Those two method set don't run, I think I know why, but I can't resolve this alone.
this.mainsJoueurs.set(numjoueur, this.mainsJoueurs.get(numjoueur).push(carte));
this.mainsJoueurs.set(numjoueur, this.mainsJoueurs.get(numjoueur).pop());
I put a commentary where the method bug.
package TP.TP5.Exercice2.Question2;
import java.util.Random;
import java.util.Vector;
import java.util.Stack;
import TP.TP5.Exercice1.Question4.Carte;
public class Belote {
private Stack<Carte> tasDistibution;
private Vector<Stack<Carte>> mainsJoueurs;
private Vector<Stack<Carte>> plisJoueurs;
public Belote() {
this.tasDistibution = new Stack<Carte>();
this.mainsJoueurs = new Vector<Stack<Carte>>(4);
this.plisJoueurs = new Vector<Stack<Carte>>(4);
for (int i = 0; i < 4; i++) {
this.mainsJoueurs.add(i, new Stack<Carte>());
this.plisJoueurs.add(i, new Stack<Carte>());
}
}
private void initialiserTasDistribution() {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= 13; j++) {
if (j == 1 || (j >= 7 && j <= 13)) {
this.tasDistibution.push(new Carte(i, j));
}
}
}
}
private void couper() {
Stack<Carte> tas1 = new Stack<Carte>();
Stack<Carte> tas2 = new Stack<Carte>();
Random r = new Random();
int coupe = 1 + r.nextInt(33 - 1);
for (int i = 0; i < coupe; i++) {
Carte carte = this.tasDistibution.peek();
this.tasDistibution.pop();
tas1.push(carte);
}
while (tasDistibution.isEmpty() == false) {
Carte carte = this.tasDistibution.peek();
this.tasDistibution.pop();
tas2.push(carte);
}
while (tas1.isEmpty() == false) {
Carte carte = tas1.peek();
tas1.pop();
this.tasDistibution.push(carte);
}
while (tas2.isEmpty() == false) {
Carte carte = tas2.peek();
tas2.pop();
this.tasDistibution.push(carte);
}
}
private void melanger(int nbMelange) {
Carte tabcarte[] = new Carte[32];
for (int i = 0; i < tabcarte.length; i++) {
Carte cartesommet = this.tasDistibution.peek();
this.tasDistibution.pop();
tabcarte[i] = cartesommet;
}
for (int i = 0; i < nbMelange; i++) {
Random r = new Random();
int pos1 = 1 + r.nextInt(32 - 1);
int pos2 = 1 + r.nextInt(32 - 1);
if (pos1 == pos2) {
System.out.println("Pas de chance");
} else {
Carte temp;
temp = tabcarte[pos1];
tabcarte[pos1] = tabcarte[pos2];
tabcarte[pos2] = temp;
}
}
for (int i = 0; i < tabcarte.length; i++) {
Carte carte = tabcarte[i];
this.tasDistibution.push(carte);
}
}
private void donnerCartesAJoueur(int nbcartedonnes, int numjoueur) {
for (int i = 0; i < nbcartedonnes; i++) {
Carte carte = this.tasDistibution.peek();
this.tasDistibution.pop();
//My problem is right here, the method set doesn't work, because the method push return a "Carte" and not a "Stack<Carte>"
//The compilateur says : The method set(int, Stack<Carte>) in the type Vector<Stack<Carte>> is not applicable for the arguments (int, Carte)
this.mainsJoueurs.set(numjoueur, this.mainsJoueurs.get(numjoueur).push(carte));
}
}
private void distribuer() {
for (int i = 0; i < 4; i++) {
this.donnerCartesAJoueur(3, i);
}
for (int i = 0; i < 4; i++) {
this.donnerCartesAJoueur(2, i);
}
for (int i = 0; i < 4; i++) {
this.donnerCartesAJoueur(3, i);
}
for (int i = 0; i < 4; i++) {
System.out.println("\n\nDistribution pour joueur : " + (i + 1) + " \n\nMain du joueur : " + (i + 1));
this.mainsJoueurs.get(i).toString();
}
}
private void assemblerPlisJoueur() {
for (int i = 0; i < 4; i++) {
while (this.plisJoueurs.get(i).isEmpty() == false) {
Carte carte = this.plisJoueurs.get(i).peek();
//Same problem here
this.plisJoueurs.set(i, this.plisJoueurs.get(i).pop());
this.tasDistibution.push(carte);
}
}
}
private void preparerPremiereManche() {
this.initialiserTasDistribution();
this.melanger(32);
this.couper();
this.distribuer();
}
private void preparerMancheSuivante() {
this.assemblerPlisJoueur();
this.couper();
this.distribuer();
}
private void jouerPli() {
Stack < Carte > tasIntermediaire = new Stack<Carte>();
for (int i = 0; i < 4; i++) {
Carte carte = this.mainsJoueurs.get(i).peek();
//Same problem here
this.mainsJoueurs.set(i, this.mainsJoueurs.get(i).pop());
tasIntermediaire.push(carte);
}
Random r = new Random();
int gagnant = 0 + r.nextInt(4 - 0);
System.out.println("Le joueur " + (gagnant + 1) + " a gagné ce pli");
for (int i = 0; i < 4; i++) {
Carte carte = tasIntermediaire.peek();
tasIntermediaire.pop();
//Same problem here
this.plisJoueurs.set(gagnant, this.plisJoueurs.get(gagnant).push(carte));
}
System.out.println("Pli du joueur " + (gagnant + 1));
this.plisJoueurs.get(gagnant).toString();
}
private void jouerManche(int nbPlis) {
for (int i = 1; i <= nbPlis; i++) {
System.out.println("\n\nPli numéro : " + i);
this.jouerPli();
}
this.preparerMancheSuivante();
}
public void jouerPartie(int nbManches) {
this.preparerPremiereManche();
for (int i = 1; i <= nbManches; i++) {
System.out.println("\n\nManche numéro : " + i);
this.jouerManche(8);
}
System.out.println("Jeu terminé");
}
}
I don't know how to resolve this problem with using only the class Stack.
Everyone have an idea can be really nice :)
(Sorry for my bad English)
The problem is that you pass in the result of the push method, which is not a Stack<Carte>, but a Carte.
Stack<Carte> stack = this.mainsJoueurs.get(numjoueur);
stack.push(carte); // this returns the added element
this.mainsJoueurs.set(numjoueur, stack);

I can not seem to create any of my objects in my main?

The point of the program is to display a poker and bridge hand. Those far when I run the program I can get it to display the poker description and then if exits. I would like it to continue and display the a poker hand then the bridge description and a bridge hand. I feel like my issues are coming from the abstract DeckOfCards class but Im really not sure.
I put all the classes in the same file to make it easier to follow and edit while programming.
When the program fails it gives these errors
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52
at DeckOfCards.creatCardDeck(PlayCardGames.java:106)
at DeckOfCards.DeckOfCards(PlayCardGames.java:95)
at PlayCardGames.main(PlayCardGames.java:14)
Here is the program code it self (Thank you for editing it to format better)
import javax.swing.*;
import java.util.Random;
public class PlayCardGames {
public static void main(String[] args) {
Poker playPoker = new Poker();
playPoker.DeckOfCards();
playPoker.displayDescription();
playPoker.deal();
Bridge playBridge = new Bridge();
playBridge.DeckOfCards();
playBridge.displayDescription();
playBridge.deal();
}
}
//--------------------------------------------------------------------------------\\
interface DeckConstants{
final static int CARDS_IN_SUIT = 13;
final static int SUITS_IN_DECK = 4;
final static int CARDS_IN_DECK = CARDS_IN_SUIT * SUITS_IN_DECK;
}
//================================================================================\\
class Card{
private String suit;
private String rank;
private int rankIndex;
public Card(int suitIndex, int rankIndex){
setSuit(suitIndex);
setRank(rankIndex);
}
public String getSuit() {
if (suit.equalsIgnoreCase("Hearts")){ suit = "\u2665";}
else if (suit.equalsIgnoreCase("Diamonds")) { suit = "\u2666"; }
else if (suit.equalsIgnoreCase("Clubs")) { suit = "\u2663"; }
else if(suit.equalsIgnoreCase("Spades")) { suit = "\u2660"; }
return suit;
}
public void setSuit(int suitIndex) {
if (suitIndex == 1) {suit = "Spades";}
else if (suitIndex == 2) {suit = "Hearts";}
else if (suitIndex == 3) {suit = "Diamonds";}
else if(suitIndex == 4) {suit = "Clubs";}
}
public String getRank() {
if (rankIndex == 1) {rank = "Ace";}
else if (rankIndex == 11) {rank = "Jack";}
else if (rankIndex == 12) {rank = "Queen";}
else if(rankIndex == 13) {rank = "King";}
return rank;
}
public void setRank(int rankIndex) {
if (this.rankIndex >= 13){
this.rankIndex = 13;}
else if(this.rankIndex <= 1) {
this.rankIndex = 1;}
}
public String toString(String rank, String suit) {
return getRank() +" of " + getSuit();
}
}
//=================================================================================\\
abstract class DeckOfCards implements DeckConstants{
protected Card[] deck = new Card[CARDS_IN_DECK];
public void DeckOfCards(){
creatCardDeck();
shuffle(deck);
}
public void creatCardDeck() {
int numberOfCards = 0;
for (int suitCounter = 1; suitCounter < CARDS_IN_SUIT; suitCounter++)
{
for (int rankCounter = 1; rankCounter < CARDS_IN_SUIT; rankCounter++)
{
deck[numberOfCards] = new Card(suitCounter, rankCounter);
numberOfCards++;
}
}
}
public void shuffle(Card[] temp){
Random rnd = new Random();
for (int k = temp.length; k > 1; k--){
int i = k - 1;
int j = rnd.nextInt(k);
Card tmp = temp[i];
temp[i] = temp[j];
temp[j]= tmp;
}
}
public abstract void displayDescription();
public abstract void deal();
}
//===============================================================================\\
class Poker extends DeckOfCards{
private int cardsDealt = 5;
private int index = 0;
public void Poker(){
displayDescription();
deal();
}
public void displayDescription(){
String desc = "In poker, players bet on hands" +
"\n Winner can bluff or must have the highest hand if called";
JOptionPane.showMessageDialog(null, desc);
}
public void deal() {
String message = "Your Poker hand:\n";
for (int x = index; x < cardsDealt; x++){
message += deck[index] + "\n";
index++;
}
if (index == CARDS_IN_DECK){
shuffle(deck);
index = 0;
}
JOptionPane.showMessageDialog(null, message);
}
}
//===============================================================================\\
class Bridge extends DeckOfCards{
private int cardsDealt = 13;
private int index = 0;
public void Bridge(){
displayDescription();
deal();
}
public void displayDescription(){
String desc = "In bride, partners bid on how many tricks they will take." +
"\n The high bid determines a trump suit";
JOptionPane.showMessageDialog(null, desc);
}
public void deal() {
String message = "Your Bridge hand:\n";
for (int x = index; x < cardsDealt; x++){
message += deck[index] + "\n";
index++;
}
if (index == CARDS_IN_DECK){
shuffle(deck);
index = 0;
}
JOptionPane.showMessageDialog(null, message);
}
}
You know what, I think it is really simple:
Here is your code:
for (int suitCounter = 1; suitCounter < CARDS_IN_SUIT; suitCounter++)
{
for (int rankCounter = 1; rankCounter < CARDS_IN_SUIT; rankCounter++)
{
I think just maybe it should be:
for (int suitCounter = 1; suitCounter < SUITS_IN_DECK; suitCounter++)
{
for (int rankCounter = 1; rankCounter < CARDS_IN_SUIT; rankCounter++)
{

Create a Matrix from an ArrayList

I want to create a class that creates a Matrix via an ArrayList.
So that's what I did:
public class Matrice implements IMatrice {
ArrayList elements;
private int numLignes;
private int numColonnes;
public static void main(String[] args) {
Matrice test = new Matrice(3, 4, 6.0);
System.out.println(test);
}
public Matrice (int numLignes, int numColonnes, double valeur){
this.numLignes = numLignes;
this.numColonnes = numColonnes;
elements = new ArrayList(numLignes * numColonnes);
for(int i = 0; i < numLignes * numColonnes; i++){
elements.add(i, valeur);
}
}
}
Now that i created this, I wanted to try if it works. Then I created this toString() method:
public String toString() {
final DecimalFormat DEC_FORMAT = new DecimalFormat("0.0");
final int ESP = 8;
int num;
String sTmp;
String s = "[";
for (int i = 0 ; i < (numLignes * numColonnes) ; i++) {
//etendre i sur ESP colonnes
sTmp = "";
num = ESP - DEC_FORMAT.format(elements.get(i)).length();
for (int j = 0 ; j < num ; j++) {
sTmp = sTmp + " ";
}
sTmp = sTmp + DEC_FORMAT.format(elements.get(i));
if (i != 0 && i % numColonnes == 0) {
s = s + " ]\n[" + sTmp;
} else {
s = s + sTmp;
}
}
s = s + " ]";
return s;
}
Then this is my main to try the Matrix:
public static void main(String[] args) {
Matrice test = new Matrice(3, 4, 6.0);
System.out.println(test);
}
and i don't know why but i only get this :
[ ]
I know that a little thing is wrong but I can't find what. Could you help me?
Okay, i messed up...
The problem was in here :
elements.add(i, valeur);
i did a mistake... i mingled with the set() method.
here is the correction :
elements.add(valeur);

Forked Java VM exited abnormally. JUnit Test?

I have a simple Java program that seems to work well until uploaded to my school's grading system, "WebCat", which I'm assuming is just running JUnit. The error it kicks back is:
Forked Java VM exited abnormally. Please note the time in the report does not reflect the >time until the VM exit.
I've researched this issue and and the main first troubleshooting step seems to be to look at the dump log. Unfortunately I cannot do that in this case. I am really at a loss on how to begin to troubleshoot this considering the lack of feedback from the grading system and the lack of compile or run-time errors.
Here is the code if anyone is familiar with this error or can at least give me some direction of where to begin troubleshooting. Much appreciated!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.IOException;
class PlayerApp {
public static void showMenu()
{
System.out.println("Player App Menu");
System.out.println("P - Print Report");
System.out.println("A - Add Score");
System.out.println("D - Delete Score");
System.out.println("L - Find Lowest Score");
System.out.println("H - Find Highest Score");
System.out.println("Q - Quit");
}
public static void main(String[] args) throws IOException
{
if (args.length == 0)
{
System.out.println("File name was expected as a run argument.");
System.out.println("Program ending.");
System.exit(0);
}
String fileName = args[0];
Scanner sc = new Scanner(System.in);
String stnew = "";
boolean exit = false;
Player p = null;
double[] scoreList;
File dbFile = new File(fileName);
FileInputStream fis = new FileInputStream(fileName);
InputStreamReader inStream = new InputStreamReader(fis);
BufferedReader stdin = new BufferedReader(inStream);
String name = stdin.readLine();
stnew = stdin.readLine();
int numScore = Integer.parseInt(stnew);
scoreList = new double[numScore];
for (int i = 0; i < numScore; i++)
{
stnew = stdin.readLine();
scoreList[i] = Double.parseDouble(stnew);
}
p = new Player(name, numScore, scoreList);
stdin.close();
System.out.println("File read in and Player object created.");
showMenu();
while (exit == false)
{
System.out.print("\nEnter Code [P, A, D, L, H, or Q]:");
String choice = sc.nextLine().toLowerCase();
if (choice.equals("p"))
{
System.out.println(p.toString());
}
else if (choice.equals("a"))
{
System.out.print(" Score to add: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.addScore(scoreIn);
}
else if (choice.equals("d"))
{
System.out.print(" Score to delete: ");
stnew = sc.nextLine();
double scoreIn = Double.parseDouble(stnew);
p.deleteScore(scoreIn);
System.out.println(" Score removed.");
}
else if (choice.equals("l"))
{
System.out.println(" Lowest score: " + p.findLowestScore());
}
else if (choice.equals("h"))
{
System.out.println(" Highest score: " + p.findHighestScore());
}
else if (choice.equals("q"))
{
exit = true;
}
}
}
}
break
import java.text.DecimalFormat;
public class Player {
//Variables
private String name;
private int numOfScores;
private double[] scores = new double[numOfScores];
//Constructor
public Player(String nameIn, int numOfScoresIn, double[] scoresIn) {
name = nameIn;
numOfScores = numOfScoresIn;
scores = scoresIn;
}
//Methods
public String getName() {
return name;
}
public double[] getScores() {
return scores;
}
public int getNumScores() {
return numOfScores;
}
public String toString() {
String res = "";
DecimalFormat twoDForm = new DecimalFormat("#,###.0#");
DecimalFormat twoEForm = new DecimalFormat("0.0");
res += " Player Name: " + name + "\n Scores: ";
for (int i = 0; i < numOfScores; i++)
{
res += twoDForm.format(scores[i]) + " ";
}
res += "\n Average Score: ";
res += twoEForm.format(this.computeAvgScore());
return res;
}
public void addScore(double scoreIn) {
double newScores[] = new double[numOfScores +1 ];
for (int i = 0; i < numOfScores; i++)
{
newScores[i] = scores[i];
}
scores = new double[numOfScores + 1];
for(int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
scores[numOfScores] = scoreIn;
numOfScores++;
}
public boolean deleteScore(double scoreIn) {
boolean found = false;
int index = 0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] == scoreIn)
{
found = true;
index = i;
}
}
if (found == true)
{
double newScores[] = new double[numOfScores -1 ];
for (int i = 0; i < index; i++)
{
newScores[i] = scores[i];
}
for (int i = index + 1; i < numOfScores; i++)
{
newScores[i - 1] = scores[i];
}
scores = new double[numOfScores - 1];
numOfScores--;
for (int i = 0; i < numOfScores; i++)
{
scores[i] = newScores[i];
}
return true;
}
else
{
return false;
}
}
public void increaseScoresCapacity()
{
scores = new double[numOfScores + 1];
numOfScores++;
}
public double findLowestScore() {
double res = 100.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] < res)
{
res = scores[i];
}
}
return res;
}
public double findHighestScore() {
double res = 0.0;
for (int i = 0; i < numOfScores; i++)
{
if (scores[i] > res)
{
res = scores[i];
}
}
return res;
}
public double computeAvgScore() {
double res = 0.0;
if (numOfScores > 0) {
for (int i = 0; i < numOfScores; i++)
{
res += scores[i];
}
return res / (double)(numOfScores);
}
else {
//res = 0.0;
return res;
}
}
}
Your program is calling System.exit(0) for certain inputs. Don't do that! That's exactly what the message is telling you: that the JVM exited in the middle of the text, before the scoring code could finish up. Instead of calling exit(), just use return to return from main() early.
The library System Rules has a JUnit rule called ExpectedSystemExit. With this rule you are able to test code, that calls System.exit(...).

Categories

Resources