Instance of object over riding another instance of the object java - java

This is for a school project In this version of the card game WAR when a tie occurs one card is faced down however my issue is occurring in the first 30 lines of code in which playerTwo is over-ridding and duplicating itself onto playerOne so that when I test my code playerOne and playerTwo are continuously 'tied'.
public class War {
public static WarQueue playerTwo;
public static WarQueue playerOne;
public static void main(String[] args) throws FileNotFoundException {
Scanner temp = new Scanner(new File("war.txt"));
{
/*String one = temp.nextLine();
String two = temp.nextLine();*/
String[] a = temp.nextLine().split(" ");
playerOne = new WarQueue(a);
String[] b = temp.nextLine().split(" ");
playerTwo = new WarQueue(b);
for (int i = 0; i < 26; i++) {
playerOne.enqueue(a[i]);
}
System.out.println(playerOne.toString());
for (int i = 0; i < 26; i++) {
playerTwo.enqueue(b[i]);
}
System.out.println(playerOne.toString());
System.out.println(playerTwo.toString());
System.out.println(playerTwo.peek());
System.out.println(playerOne.peek());
System.out.println(playerOne.peek() + " " + playerTwo.peek());
int hand = hand(playerOne.peek(), playerTwo.peek());
if (hand == 1) {
playerOne.enqueue(playerOne.dequeue());
playerOne.enqueue(playerTwo.dequeue());
System.out.println(playerOne.peek());
} else if (hand == 2) {
playerTwo.enqueue(playerTwo.dequeue());
playerTwo.enqueue(playerOne.dequeue());
System.out.println(playerTwo.peek());
} else {
ArrayList<String> warCards = new ArrayList<>();
String first = null;
String second = null;
int win = 0;
do {
String down1 = playerOne.dequeue();
String down2 = playerTwo.dequeue();
first = playerOne.dequeue();
second = playerTwo.dequeue();
warCards.add(down1);
warCards.add(down2);
warCards.add(first);
warCards.add(second);
win = hand(first, second);
} while (win == 10);
if (win == 1) {
for (String card : warCards) {
playerOne.enqueue(card);
}
} else if (win == 2) {
for (String card : warCards) {
playerTwo.enqueue(card);
}
}
warCards.clear();
}
if (playerOne.size() == 52) {
System.out.println("player 1 wins");
} else {
System.out.println("player 2 wins");
}
} while (temp.hasNextLine());
}
static int hand(String one, String two) {
String[] card = one.split("");
String[] card2 = two.split("");
int cardOne = 0;
int cardTwo = 0;
int win = 0;
switch (card[0]) {
case "T":
cardOne = 10;
break;
case "J":
cardOne = 11;
break;
case "Q":
cardOne = 12;
break;
case "K":
cardOne = 13;
break;
case "A":
cardOne = 14;
break;
case "2":
cardOne = 2;
break;
case "3":
cardOne = 3;
break;
case "4":
cardOne = 4;
break;
case "5":
cardOne = 5;
break;
case "6":
cardOne = 6;
break;
case "7":
cardOne = 7;
break;
case "8":
cardOne = 8;
break;
case "9":
cardOne = 9;
break;
}
switch (card2[0]) {
case "T":
cardTwo = 10;
break;
case "J":
cardTwo = 11;
break;
case "Q":
cardTwo = 12;
break;
case "K":
cardTwo = 13;
break;
case "A":
cardTwo = 14;
break;
case "2":
cardTwo = 2;
break;
case "3":
cardTwo = 3;
break;
case "4":
cardTwo = 4;
break;
case "5":
cardTwo = 5;
break;
case "6":
cardTwo = 6;
break;
case "7":
cardTwo = 7;
break;
case "8":
cardTwo = 8;
break;
case "9":
cardTwo = 9;
break;
}
if (cardOne > cardTwo)
win = 1;
if (cardTwo > cardOne)
win = 2;
if (cardOne == cardTwo)
win = 10;
return win;
}
}
this is my WarQueue class
public class WarQueue {
/**
* Created by 148439 on 9/4/2018.
*/
public static String[] ringBuffer;
int front = 0;
int size = 0;
WarQueue(String[] a )
{
ringBuffer = new String[a.length];
}// create an empty ring buffer, with given max capacity
int size()
{
return size;
}// return number of items currently in the buffer
boolean isEmpty()
{
return size() == 0;
}// is the buffer empty (size equals zero)?
boolean isFull()
{
return size() == ringBuffer.length;
}
// buffer full (size equals capacity)?
void enqueue(String b)
{
if (isFull()) {
return;
}
ringBuffer[(front + size()) % ringBuffer.length] = String.valueOf(b);
size++;
}// add item x to the end
String dequeue()
{
if (isEmpty())
return null;
String pos = ringBuffer[front];
front = (front + 1) % ringBuffer.length;
size--;
return pos;
}// delete and return item from the front
String peek()
{
if (isEmpty())
{
return null;
}
return ringBuffer[front];
}
void empty() {
ringBuffer = new String[ringBuffer.length];
front = 0;
size = 0;
}
public String toString()
{
String str = "";
for(int i = 0; i < ringBuffer.length; i++)
{
str = str + " " + ringBuffer[i];
}
return str;
}
}
this code prints out that playerOne and playerTwo are the same but when tested in their own for loops they are diffrent until after the second for loop ends.

Related

Build Blackjack program in Java, but "split" method would require rewriting whole program?

Getting back into programming after many years, and build a simple "blackjack" program in Java.
I'm wondering if the way I structured the methods/objects is bad, using global static variables. The program seems to work fine, but there's no way to implement a "split" method without re-writing everything, since you can't pass the new "split" hands into the "hit" or "stand" functions.
I'm curious how others would structure this and what the flaws in my methodology were. Thanks!
import java.io.*;
import java.util.*;
public class BlackJack {
static int bankroll = 0;
static int bet = 1;
static int index = 0;
static CardDeck d = new CardDeck();
static ArrayList<Card> playerCards = new ArrayList<Card>();
static ArrayList<Card> playerCards2 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards3 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards4 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards5 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> playerCards6 = new ArrayList<Card>(); //unused - was thinking of using for splitting
static ArrayList<Card> dealerCards = new ArrayList<Card>(); //unused - was thinking of using for splitting
static int playerScore = 0;
static int dealerScore = 0;
static String action = "";
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
initializeBankroll();
while (bet != 0) {
startRound();
display();
if(checkBlackJacks()) continue;
while (playerScore <= 21) {
System.out.println("H - hit, S - stand, X - surrender, D - double down");
action = s.nextLine();
if (action.equals("H")) hit();
else if (action.equals("S")) {
stand();
break;
}
else if (action.equals("X")) surrender();
else if (action.equals("D")) {
doubleDown();
break;
}
}
eval();
}
}
public static int score (ArrayList<Card> list) {
int ret = 0;
int acecounter = 0;
for (int i=0; i<list.size(); i++) {
if (list.get(i).getVal()>1) {
ret += Math.min(10, list.get(i).getVal());
}
else { //An ace
ret += 11;
acecounter++;
}
}
while(ret >21 && acecounter >0) {
ret -= 10;
acecounter -= 1;
}
return ret;
}
public static void dealToPlayer() {
playerCards.add(d.getCard(index));
index++;
}
public static void dealToDealer() {
dealerCards.add(d.getCard(index));
index++;
}
public static void display() {
System.out.println("PLAYER CARDS:");
String playerCardString = "";
for (int i=0; i<playerCards.size(); i++) {
playerCardString += playerCards.get(i).toString();
playerCardString += " ";
}
System.out.println(playerCardString);
System.out.println("DEALER CARD:");
System.out.println(dealerCards.get(0).toString());
}
public static void hit() {
dealToPlayer();
reScore();
display();
}
public static void surrender() {
if(playerCards.size()>2) {
System.out.println("You can't do that");
return;
}
bankroll -= (bet / 2);
playerScore = 100; //surrender
}
public static void reScore() {
playerScore = score(playerCards);
dealerScore = score(dealerCards);
}
public static void stand() {
try {
System.out.println("DEALER DOWNCARD: " + dealerCards.get(1).toString());
Thread.sleep(1000);
while (dealerScore <17) {
dealToDealer();
System.out.println(dealerCards.get(dealerCards.size()-1).toString());
reScore();
System.out.println("DEALER SCORE " + Integer.toString(dealerScore));
Thread.sleep(1000);
}
}catch(Exception E) {
System.out.println("Exception");
}
}
public static void doubleDown() {
if(playerCards.size()>2) {
System.out.println("You can't do that, hitting instead");
hit();
if(playerScore<=21) stand();
return;
}
if( bet * 2 > bankroll) {
System.out.println("Doubling for less...");
bet = bankroll;
hit();
if(playerScore<=21) stand();
return;
}
bet *= 2;
hit();
if(playerScore<=21) stand();
}
public static void split(ArrayList<Card> splitarray, int splitcount) { //INCOMPLETE. How to get this to work?
if(splitarray.size()>2 || bet * (splitcount+1) > bankroll || splitarray.get(1).getVal() != splitarray.get(0).getVal()) {
System.out.println("Can't split. Hitting instead");
hit();
}
ArrayList<Card> s1 = new ArrayList<Card>();
ArrayList<Card> s2 = new ArrayList<Card>();
s1.add(splitarray.get(0));
s2.add(splitarray.get(1));
}
public static void eval() {
if (playerScore==100) { //indicates a surrender, and bankroll has already been adjusted
return;
}
if (playerScore>21) {
System.out.println("BUST");
bankroll -= bet;
return;
}
if (dealerScore>21) {
System.out.println("DEALER BUST");
bankroll += bet;
return;
}
if (playerScore > dealerScore) {
System.out.println("WIN");
bankroll += bet;
return;
}
if (playerScore < dealerScore) {
System.out.println("LOSE");
bankroll -= bet;
return;
}
System.out.println("PUSH");
return;
}
public static void newhand() {
d.shuffle();
playerCards.clear();
dealerCards.clear();
index = 0;
reScore();
}
public static boolean checkBlackJacks() {
if(playerScore == 21) {
if(dealerCards.get(0).getVal()==1) {
System.out.println("Even money? Y / N");
String even = s.nextLine();
if (even=="Y"){
bankroll += bet;
newhand();
return true;
}
}
if(dealerScore != 21) {
System.out.println("BlackJack");
bankroll += (1.5 * bet);
newhand();
return true;
}
else {
System.out.println("Push - Mutual Blackjack");
newhand();
return true;
}
}
if(dealerCards.get(0).getVal()==1) { //insurance
System.out.println("Insurance? Type wager or 0, up to half your bet");
int insuranceBet = s.nextInt();
if (insuranceBet > bankroll) insuranceBet = bankroll;
if (insuranceBet > (bet / 2)) insuranceBet = bet / 2;
if (dealerScore == 21) bankroll += (insuranceBet * 2);
else bankroll -= insuranceBet;
}
if(dealerScore==21) {
System.out.println("Dealer Blackjack");
bankroll -= bet;
newhand();
return true;
}
return false;
}
public static void initializeBankroll() {
System.out.println("Enter your buy-in");
bankroll = s.nextInt();
}
public static void startRound() {
newhand();
System.out.println("Money remaining:" + Integer.toString(bankroll));
System.out.println("Enter your bet");
bet = s.nextInt();
if (bet>bankroll) bet=0;
dealToPlayer();
dealToDealer();
dealToPlayer();
dealToDealer();
reScore();
}
}
___________________
public class Card {
int val; //1 = Ace, 11 = Jack, 12 = Queen, 13 = King
int suit; //1 = Club, 2 = Diamond, 3 = Heart, 4 = Spade
public Card() {
this(1,1);
}
public Card(int val, int suit) {
this.val = val;
this.suit = suit;
}
public int getSuit(){
return suit;
}
public int getVal() {
return val;
}
public void setVal(int a) {
if(a>=1 && a<= 13) val = a;
}
public void setSuit(int a) {
if (a>=1 && a<=4) suit = a;
}
public String toString() {
String valString = "";
String suitString = "";
String ret = "";
switch(val) {
case 1: valString = "A"; break;
case 10: valString = "T"; break;
case 11: valString = "J"; break;
case 12: valString = "Q"; break;
case 13: valString = "K"; break;
default: valString = Integer.toString(val);
}
switch(suit) {
case 1: suitString = "c"; break;
case 2: suitString = "d"; break;
case 3: suitString = "h"; break;
case 4: suitString = "s"; break;
default: suitString = "ERROR"; break;
}
ret = valString + suitString;
return ret;
}
}
______________________
public class CardDeck{
Card[] deck;
public CardDeck(){
int k=0;
deck = new Card[52];
for (int i=0; i<13; i++){
for (int j=0; j<4; j++){
Card c = new Card(i+1,j+1);
deck[k]=c;
k++;
}
}
shuffle();
}
public void shuffle(){
Card[] deckCopy = new Card[52];
boolean[] flags = new boolean[52];
for (int i=0; i<flags.length; i++) flags[i]=false;
int numConverted=0;
while(numConverted<52){
int num = (int)(Math.random() * 52);
if (flags[num]==false){
deckCopy[numConverted]=deck[num];
numConverted++;
flags[num]=true;
}
}
deck = deckCopy;
} //end shuffle
public String toString() {
String ret = "";
for (int i = 0; i<deck.length; i++) {
ret += deck[i].toString();
ret += " ";
}
return ret;
}
public Card getCard(int a) {
if (a<0 || a > 51) return null;
else return deck[a];
}
public int getSuit(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getSuit();
}
public int getVal(int a) {
if (a<0 || a > 51) return 0;
else return deck[a].getVal();
}
}

Blackjack game - How to use the getter and the toString() methods

I'm trying to learn Java and I copied a program that simulate a blackjack game (from here: https://www.youtube.com/watch?v=buGFs1aQgaY).
I understood most of it but I got stuck at how the program make the sum of an hand. In the forth class, called "Player", at some point there is:
cardNum = this.hand[c].getNumber();
Let's say that:
this.hand[c] = King of Clubs.
I don't understand how the program gives as a result:
cardNum = 13.
How does the getNumber method works? (The method is made in the first class, called Card)
I'll post all the classes of the program.
FIRST CLASS.
public class Card {
private Suit mySuit;
private int myNumber;
public Card(Suit aSuit, int aNumber){
this.mySuit = aSuit;
if (aNumber >= 1 && aNumber <= 13){
this.myNumber = aNumber;
} else{
System.err.println(aNumber + " is not a valid Card number");
System.exit(1);
}}
public int getNumber(){
return myNumber;
}
public String toString(){
String numStr = "Err";
switch(this.myNumber){
case 2:
numStr = "Two";
break;
case 3:
numStr = "Three";
break;
case 4:
numStr = "Four";
break;
case 5:
numStr = "Five";
break;
case 6:
numStr = "Six";
break;
case 7:
numStr = "Seven";
break;
case 8:
numStr = "Eight";
break;
case 9:
numStr = "Nine";
break;
case 10:
numStr = "Ten";
break;
case 11:
numStr = "Jack";
break;
case 12:
numStr = "Queen";
break;
case 13:
numStr = "King";
break;
case 1:
numStr = "Ace";
break;
}
return numStr + " of " + mySuit.toString();
}
}
SECOND CLASS
public enum Suit {
Clubs,
Diamonds,
Spades,
Hearts
}
THIRD CLASS
import java.util.Random;
public class Deck {
private Card[] myCards;
private int numCards;
public Deck(){
this(1,false);
}
public Deck(int numDecks, boolean shuffle) {
this.numCards = numDecks * 52;
this.myCards = new Card[this.numCards];
int c = 0;
for (int d = 0; d < numDecks; d++) {
for (int s = 0; s < 4; s++) {
for (int n = 1; n <= 13; n++) {
this.myCards[c] = new Card(Suit.values()[s], n);
c++;
}
}
}
if (shuffle) {
this.shuffle();
}
}
public void shuffle(){
Random rng = new Random();
Card temp;
int j;
for (int i = 0; i < this.numCards; i++){
j = rng.nextInt(this.numCards);
temp = this.myCards[i];
this.myCards[i] = this.myCards[j];
this.myCards[j] = temp;
}
}
public Card dealNextCard() {
Card top = this.myCards[0];
for (int c = 1; c < this.numCards; c++) {
this.myCards[c - 1] = this.myCards[c];
}
this.myCards[this.numCards - 1] = null;
this.numCards--;
return top;
}
public void printDeck(int numToPrint){
for(int c=0; c < numToPrint; c++) {
System.out.printf("% 3d/%d/%s\n", c + 1, this.numCards,
this.myCards[c].toString());
}
System.out.printf("/t/t[%d other]\n", this.numCards-numToPrint);
}
}
FORTH CLASS
public class Player {
private String name;
private Card[]hand = new Card[10];
private int numCards;
public Player(String aName) {
this.name = aName;
this.emptyHand();
}
public void emptyHand(){
for(int c=0; c<10; c++){
this.hand[c] = null;
}
this.numCards = 0;
}
public boolean addCard(Card aCard) {
if (this.numCards == 10) {
System.err.printf("%s's hand already has 10 cards;" +
"cannot add another\n", this.name);
System.exit(1);
}
this.hand[this.numCards] = aCard;
this.numCards++;
return(this.getHandSum()<= 21);
}
public int getHandSum(){
int handSum = 0;
int cardNum;
int numAces = 0;
for(int c=0; c < this.numCards; c++) {
cardNum = this.hand[c].getNumber();
if (cardNum == 1) {
numAces++;
handSum += 11;
} else if (cardNum > 10) {
handSum += 10;
} else {
handSum += cardNum;
}
}
while (handSum >21 && numAces > 0){
handSum -= 10;
numAces--;
}
return handSum;
}
public void printHand(boolean showFirstCard){
System.out.printf("%s's cards:\n", this.name);
for(int c=0; c<this.numCards; c++) {
if(c==0 && !showFirstCard) {
System.out.println(" [hidden]");
} else {
System.out.printf(" %s\n", this.hand[c].toString());
}
}
}
}
FIFTH CLASS - PROGRAM
import java.util.Scanner;
public class GameRunner{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Deck theDeck = new Deck(1, true);
theDeck.printDeck(52);
Player me = new Player("Player 1");
Player dealer = new Player("Dealer");
me.addCard(theDeck.dealNextCard());
dealer.addCard(theDeck.dealNextCard());
me.addCard(theDeck.dealNextCard());
dealer.addCard(theDeck.dealNextCard());
System.out.println("Cards are dealt\n");
me.printHand(true);
dealer.printHand(false);
System.out.println("\n");
boolean meDone = false;
boolean dealerDone = false;
String ans;
while(!meDone || !dealerDone) {
if(!meDone){
System.out.println("Hit or Stay? (Enter H or S):");
ans = sc.next();
System.out.println();
if(ans.compareToIgnoreCase("H") == 0) {
meDone = !me.addCard(theDeck.dealNextCard());
me.printHand(true);
} else {
meDone = true;
}
}
if(!dealerDone){
if (dealer.getHandSum() < 17) {
System.out.println("The Dealer hits\n");
dealerDone = !dealer.addCard(theDeck.dealNextCard());
dealer.printHand(false);
} else {
System.out.println("The Dealer stays\n");
dealerDone = true;
}
}
System.out.println();
}
sc.close();
me.printHand(true);
dealer.printHand(true);
int mySum = me.getHandSum();
int dealerSum = dealer.getHandSum();
if(mySum > dealerSum && mySum <= 21 || dealerSum>21) {
System.out.println("Your win");
} else{
System.out.println("Dealer wins!");
}
}
}
When you create each instance of class Card, you pass in a Suit and a VALUE for that card:
... = new Card(Suit.values()[s], n);
In the above example from the code, the n variable is the value of the card, and was going from 1 to 13 because of the for loops setup to create the decks of cards.
In the Constructor for class Card, we then store that value in the private member called myNumber seen below:
public class Card {
private Suit mySuit;
private int myNumber; // <-- the value of the card is stored here
public Card(Suit aSuit, int aNumber){
// ... other code ...
this.myNumber = aNumber; // <-- store the passed in value in the instance member
// ... other code ...
}
}
Finally, the getNumber() function simply returns the stored value of the card, previously put into myNumber:
public int getNumber(){
return myNumber;
}

DeckOfCards and HighLow Class incompatible types

I get an incompatible types error when running my code. It is when "playerGuess = d1.deal();"
Thank you in advanced. This main has two other classes that go along with it. The DeckOfCards and Cards Classes.
Card Class
public class Card
{
public final static int ACE = 1;
public final static int TWO = 2;
public final static int THREE = 3;
public final static int FOUR = 4;
public final static int FIVE = 5;
public final static int SIX = 6;
public final static int SEVEN = 7;
public final static int EIGHT = 8;
public final static int NINE = 9;
public final static int TEN = 10;
public final static int JACK = 11;
public final static int QUEEN = 12;
public final static int KING = 13;
public final static int CLUBS = 1;
public final static int DIAMONDS = 2;
public final static int HEARTS = 3;
public final static int SPADES = 4;
private final static int NUM_FACES = 13;
private final static int NUM_SUITS = 4;
private int face, suit;
private String faceName, suitName;
//-----------------------------------------------------------------
// Creates a random card.
//-----------------------------------------------------------------
public Card()
{
face = (int) (Math.random() * NUM_FACES) + 1;
setFaceName();
suit = (int) (Math.random() * NUM_SUITS) + 1;
setSuitName();
}
//-----------------------------------------------------------------
// Creates a card of the specified suit and face value.
//-----------------------------------------------------------------
public Card(int faceValue, int suitValue)
{
face = faceValue;
setFaceName();
suit = suitValue;
setSuitName();
}
//-----------------------------------------------------------------
// Sets the string representation of the face using its stored
// numeric value.
//-----------------------------------------------------------------
private void setFaceName()
{
switch (face)
{
case ACE:
faceName = "Ace";
break;
case TWO:
faceName = "Two";
break;
case THREE:
faceName = "Three";
break;
case FOUR:
faceName = "Four";
break;
case FIVE:
faceName = "Five";
break;
case SIX:
faceName = "Six";
break;
case SEVEN:
faceName = "Seven";
break;
case EIGHT:
faceName = "Eight";
break;
case NINE:
faceName = "Nine";
break;
case TEN:
faceName = "Ten";
break;
case JACK:
faceName = "Jack";
break;
case QUEEN:
faceName = "Queen";
break;
case KING:
faceName = "King";
break;
}
}
//-----------------------------------------------------------------
// Sets the string representation of the suit using its stored
// numeric value.
//-----------------------------------------------------------------
private void setSuitName()
{
switch (suit)
{
case CLUBS:
suitName = "Clubs";
break;
case DIAMONDS:
suitName = "Diamonds";
break;
case HEARTS:
suitName = "Hearts";
break;
case SPADES:
suitName = "Spades";
break;
}
}
//-----------------------------------------------------------------
// Determines if this card is higher than the passed card. The
// second parameter determines if aces should be considered high
// (beats a King) or low (lowest of all cards). Uses the suit
// if both cards have the same face.
//-----------------------------------------------------------------
public boolean isHigherThan(Card card2, boolean aceHigh)
{
boolean result = false;
if (face == card2.getFace())
{
if (suit > card2.getSuit())
result = true;
}
else
{
if (aceHigh && face == ACE)
result = true;
else
if (face > card2.getFace())
result = true;
}
return result;
}
//-----------------------------------------------------------------
// Determines if this card is higher than the passed card,
// assuming that aces should be considered high.
//-----------------------------------------------------------------
public boolean isHigherThan(Card card2)
{
return isHigherThan(card2, true);
}
//-----------------------------------------------------------------
// Returns the face (numeric value) of this card.
//-----------------------------------------------------------------
public int getFace()
{
return face;
}
//-----------------------------------------------------------------
// Returns the suit (numeric value) of this card.
//-----------------------------------------------------------------
public int getSuit()
{
return suit;
}
//-----------------------------------------------------------------
// Returns the face (string value) of this card.
//-----------------------------------------------------------------
public String getFaceName()
{
return faceName;
}
//-----------------------------------------------------------------
// Returns the suit (string value) of this card.
//-----------------------------------------------------------------
public String getSuitName()
{
return suitName;
}
//-----------------------------------------------------------------
// Returns the string representation of this card, including
// both face and suit.
//-----------------------------------------------------------------
public String toString()
{
return faceName + " of " + suitName;
}
}
Deck of Cards Class
public class DeckOfCards
{
private Card[] myCardDeck;
private int nowCard;
public DeckOfCards( ) {
myCardDeck = new Card[ 52 ];
int i = 0;
for ( int suit = Card.SPADES; suit <= Card.DIAMONDS; suit++ )
for ( int pos = 1; pos <= 13; pos++ )
myCardDeck[i++] = new Card(suit, pos);
nowCard = 0;
}
public void shuffle(int n)
{
int i, j, k;
for ( k = 0; k < n; k++ )
{
i = (int) ( 52 * Math.random() );
j = (int) ( 52 * Math.random() );
Card tmp = myCardDeck[i];
myCardDeck[i] = myCardDeck[j];
myCardDeck[j] = tmp;;
}
nowCard = 0;
}
public Card deal()
{
if ( nowCard < 52 )
{
return ( myCardDeck[ nowCard++ ] );
}
else
{
System.out.println("No Cards BRUH");
return ( null );
}
}
public String toString()
{
String s = "";
int Q = 0;
for ( int i = 0; i < 4; i++ )
{
for ( int j = 1; j <= 13; j++ )
s += (myCardDeck[Q++] + " ");
s += "\n";
}
return ( s );
}
public int deckSize()
{
for(int z =0; z < myCardDeck.length && z < 52; z++);
return myCardDeck.length;
}
}
The main driver class (HighLow)
import java.util.*;
public class HighLow
{
public static void main (String [] args)
{
DeckOfCards d1 = new DeckOfCards();
Scanner scan = new Scanner(System.in);
String playerGuess;
Card firstDeal, secondDeal;
int count =0;
d1.shuffle(1);
firstDeal = d1.deal();
while(true)
{
if(d1.deckSize() == 0);
{
System.out.print("Game over! Score: " + count);
break;
}
System.out.print(firstDeal);
System.out.print("Guess if next card will be a high card, or a low card!");
System.out.print("Use H or L");
playerGuess = d1.deal();
if(secondDeal.isHigherThan(firstDeal)&&playerGuess.equals("H"))
{
System.out.print("Nice!!!!");
count++;
firstDeal=secondDeal;
}
else if(firstDeal.isHigherThan(secondDeal) && playerGuess.equals("L"))
{
System.out.println("NICE!!!!");
count++;
firstDeal = secondDeal;
}
else if (firstDeal.isHigherThan(secondDeal) && playerGuess.equals("L"))
{
System.out.print("Good Job!!!!");
count++;
firstDeal = secondDeal;
}
else
{
System.out.println("Sorry, the game is over. But your score is! " + count);
break;
}
}
}}
Thank you!
The method deal() returns a Card:
public Card deal() { ... }
The variable playerGuess is a String:
String playerGuess;
You can't assign a Card to a String:
playerGuess = d1.deal(); // incompatible types
It looks like you want playerGuess to store the user input, so it should be:
playerGuess = scan.next();

Transforming code from C to Java

#include <stdio.h>
#include <stdlib.h>
#define ST_PARAMETROV 4 //stevilo vhodnih parametrov
#define VEL_SPOMINA 10000 //velikost spomina +-10000
#define VEL_PROGRAMA 10000 //največja velikost programa
#define DOVOLJENIH_UKAZOV 10000 //največje dovoljeno število ukazov
int main() {
// \0 označuje konec programa
char program[VEL_PROGRAMA] = ",.>,<<,->--->+++.<.<.\0";
int programPointer = 0;
char parametri[ST_PARAMETROV] = {20,30,40,50};
int parametriPointer = 0;
unsigned char spomin[VEL_SPOMINA*2] = {0};
int spominPointer = VEL_SPOMINA;
int stOklepajev;
int stOpravljenihUkazov = 0;
while(program[programPointer] != 0 && DOVOLJENIH_UKAZOV > stOpravljenihUkazov){
switch(program[programPointer]){
case '>':
spominPointer ++;
break;
case '<':
spominPointer --;
break;
case '+':
spomin[spominPointer] ++;
break;
case '-':
spomin[spominPointer] --;
break;
case '.':
printf("%i\n",spomin[spominPointer]);
break;
case ',':
//če je zmanka parametrov zapiše 0
if(parametriPointer > ST_PARAMETROV-1)spomin[spominPointer] = 0;
else spomin[spominPointer] = parametri[parametriPointer++];
break;
case '[':
if(spomin[spominPointer] == 0){
stOklepajev = 1;
while(stOklepajev != 0){
programPointer ++;
if(program[programPointer] == ']'){
stOklepajev--;
}
if(program[programPointer] == '['){
stOklepajev++;
}
}
}
break;
case ']':
if(spomin[spominPointer] != 0){
stOklepajev = 1;
while(stOklepajev != 0){
programPointer--;
if(program[programPointer] == '['){
stOklepajev--;
}
if(program[programPointer] == ']'){
stOklepajev++;
}
}
}
break;
}
programPointer ++;
stOpravljenihUkazov++;
}
return 0;
}
Hi could anybody help me please, I am having some difficulties transforming this code from C language to Java language, could anybody who can do this without any problems and with an ease. I already tried it to transfrom it into Java, but I fail everytime with many errors.
I would really appreciate if someone could just tranform the code into Java and then I will correct the errors myself.
Code itself is a Brainfuck interpreter.
Thanks
Your #defines will probably have to be const char.
Your case switches will have to be converted to
if
else if
else if
...
else
After that it should be fairly simple.
The needful transformations are limited to class and object definitions/initialization and return:
public class Brainfuck
{
final static int
ST_PARAMETROV = 4, //stevilo vhodnih parametrov
VEL_SPOMINA = 10000, //velikost spomina +-10000
VEL_PROGRAMA = 10000, //najve?ja velikost programa
DOVOLJENIH_UKAZOV = 10000; //najve?je dovoljeno ?tevilo ukazov
public static void main(String[] argv)
{
// \0 ozna?uje konec programa
char program[] = new char[VEL_PROGRAMA];
char initialProgram[] = ",.>,<<,->--->+++.<.<.\0".toCharArray();
System.arraycopy(initialProgram, 0, program, 0, initialProgram.length);
int programPointer = 0;
char parametri[] = {20, 30, 40, 50};
int parametriPointer = 0;
char spomin[] = new char[VEL_SPOMINA*2];
int spominPointer = VEL_SPOMINA;
int stOklepajev;
int stOpravljenihUkazov = 0;
while (program[programPointer] != 0
&& DOVOLJENIH_UKAZOV > stOpravljenihUkazov)
{
switch (program[programPointer])
{
case '>':
spominPointer++;
break;
case '<':
spominPointer--;
break;
case '+':
spomin[spominPointer]++;
break;
case '-':
spomin[spominPointer]--;
break;
case '.':
System.out.println((int)spomin[spominPointer]);
break;
case ',':
//?e je zmanka parametrov zapi?e 0
if (parametriPointer > ST_PARAMETROV-1)
spomin[spominPointer] = 0;
else spomin[spominPointer] = parametri[parametriPointer++];
break;
case '[':
if (spomin[spominPointer] == 0)
{
stOklepajev = 1;
while (stOklepajev != 0)
{
programPointer++;
if(program[programPointer] == ']') stOklepajev--;
if(program[programPointer] == '[') stOklepajev++;
}
}
break;
case ']':
if(spomin[spominPointer] != 0)
{
stOklepajev = 1;
while(stOklepajev != 0)
{
programPointer--;
if(program[programPointer] == '[') stOklepajev--;
if(program[programPointer] == ']') stOklepajev++;
}
}
break;
}
programPointer++;
stOpravljenihUkazov++;
}
System.exit(0);
}
}

how to convert a char array back into string [duplicate]

This question already has answers here:
How to convert a char array back to a string?
(14 answers)
Closed 9 years ago.
i am doing a porter stemmer.....the code gives me output in char array....but i need to convert that into string to proceed with futher work.....in the code i have given 2 words "looking" and "walks"....that is returned as look and walk(but in char array)...the output is printed in stem() function
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package file;
import java.util.Vector;
/**
*
* #author sky
*/
public class stemmer {
public static String line1;
private char[] b;
private int i, /* offset into b */
i_end, /* offset to end of stemmed word */
j, k;
private static final int INC = 50;
/* unit of size whereby b is increased */
public stemmer()
{
//b = new char[INC];
i = 0;
i_end = 0;
}
/**
* Add a character to the word being stemmed. When you are finished
* adding characters, you can call stem(void) to stem the word.
*/
public void add(char ch)
{
System.out.println("in add() function");
if (i == b.length)
{
char[] new_b = new char[i+INC];
for (int c = 0; c < i; c++)
new_b[c] = b[c];
b = new_b;
}
b[i++] = ch;
}
/** Adds wLen characters to the word being stemmed contained in a portion
* of a char[] array. This is like repeated calls of add(char ch), but
* faster.
*/
public void add(char[] w, int wLen)
{ if (i+wLen >= b.length)
{
char[] new_b = new char[i+wLen+INC];
for (int c = 0; c < i; c++)
new_b[c] = b[c];
b = new_b;
}
for (int c = 0; c < wLen; c++)
b[i++] = w[c];
}
public void addstring(String s1)
{
b=new char[s1.length()];
for(int k=0;k<s1.length();k++)
{
b[k] = s1.charAt(k);
System.out.println(b[k]);
}
i=s1.length();
}
/**
* After a word has been stemmed, it can be retrieved by toString(),
* or a reference to the internal buffer can be retrieved by getResultBuffer
* and getResultLength (which is generally more efficient.)
*/
public String toString() { return new String(b,0,i_end); }
/**
* Returns the length of the word resulting from the stemming process.
*/
public int getResultLength() { return i_end; }
/**
* Returns a reference to a character buffer containing the results of
* the stemming process. You also need to consult getResultLength()
* to determine the length of the result.
*/
public char[] getResultBuffer() { return b; }
/* cons(i) is true <=> b[i] is a consonant. */
private final boolean cons(int i)
{ switch (b[i])
{ case 'a': case 'e': case 'i': case 'o': case 'u': return false;
case 'y': return (i==0) ? true : !cons(i-1);
default: return true;
}
}
/* m() measures the number of consonant sequences between 0 and j. if c is
a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
....
*/
private final int m()
{ int n = 0;
int i = 0;
while(true)
{ if (i > j) return n;
if (! cons(i)) break; i++;
}
i++;
while(true)
{ while(true)
{ if (i > j) return n;
if (cons(i)) break;
i++;
}
i++;
n++;
while(true)
{ if (i > j) return n;
if (! cons(i)) break;
i++;
}
i++;
}
}
/* vowelinstem() is true <=> 0,...j contains a vowel */
private final boolean vowelinstem()
{ int i; for (i = 0; i <= j; i++) if (! cons(i)) return true;
return false;
}
/* doublec(j) is true <=> j,(j-1) contain a double consonant. */
private final boolean doublec(int j)
{ if (j < 1) return false;
if (b[j] != b[j-1]) return false;
return cons(j);
}
/* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short word. e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
*/
private final boolean cvc(int i)
{ if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
{ int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
}
private final boolean ends(String s)
{
int l = s.length();
int o = k-l+1;
if (o < 0)
return false;
for (int i = 0; i < l; i++)
if (b[o+i] != s.charAt(i))
return false;
j = k-l;
return true;
}
/* setto(s) sets (j+1),...k to the characters in the string s, readjusting
k. */
private final void setto(String s)
{ int l = s.length();
int o = j+1;
for (int i = 0; i < l; i++)
b[o+i] = s.charAt(i);
k = j+l;
}
/* r(s) is used further down. */
private final void r(String s) { if (m() > 0) setto(s); }
/* step1() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet
*/
private final void step1()
{
if (b[k] == 's')
{ if (ends("sses")) k -= 2; else
if (ends("ies")) setto("i"); else
if (b[k-1] != 's') k--;
}
if (ends("eed")) { if (m() > 0) k--; } else
if ((ends("ed") || ends("ing")) && vowelinstem())
{ k = j;
if (ends("at")) setto("ate"); else
if (ends("bl")) setto("ble"); else
if (ends("iz")) setto("ize"); else
if (doublec(k))
{ k--;
{ int ch = b[k];
if (ch == 'l' || ch == 's' || ch == 'z') k++;
}
}
else if (m() == 1 && cvc(k)) setto("e");
}
}
/* step2() turns terminal y to i when there is another vowel in the stem. */
private final void step2() { if (ends("y") && vowelinstem()) b[k] = 'i'; }
/* step3() maps double suffices to single ones. so -ization ( = -ize plus
-ation) maps to -ize etc. note that the string before the suffix must give
m() > 0. */
private final void step3() { if (k == 0) return; /* For Bug 1 */ switch (b[k-1])
{
case 'a': if (ends("ational")) { r("ate"); break; }
if (ends("tional")) { r("tion"); break; }
break;
case 'c': if (ends("enci")) { r("ence"); break; }
if (ends("anci")) { r("ance"); break; }
break;
case 'e': if (ends("izer")) { r("ize"); break; }
break;
case 'l': if (ends("bli")) { r("ble"); break; }
if (ends("alli")) { r("al"); break; }
if (ends("entli")) { r("ent"); break; }
if (ends("eli")) { r("e"); break; }
if (ends("ousli")) { r("ous"); break; }
break;
case 'o': if (ends("ization")) { r("ize"); break; }
if (ends("ation")) { r("ate"); break; }
if (ends("ator")) { r("ate"); break; }
break;
case 's': if (ends("alism")) { r("al"); break; }
if (ends("iveness")) { r("ive"); break; }
if (ends("fulness")) { r("ful"); break; }
if (ends("ousness")) { r("ous"); break; }
break;
case 't': if (ends("aliti")) { r("al"); break; }
if (ends("iviti")) { r("ive"); break; }
if (ends("biliti")) { r("ble"); break; }
break;
case 'g': if (ends("logi")) { r("log"); break; }
} }
/* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */
private final void step4() { switch (b[k])
{
case 'e': if (ends("icate")) { r("ic"); break; }
if (ends("ative")) { r(""); break; }
if (ends("alize")) { r("al"); break; }
break;
case 'i': if (ends("iciti")) { r("ic"); break; }
break;
case 'l': if (ends("ical")) { r("ic"); break; }
if (ends("ful")) { r(""); break; }
break;
case 's': if (ends("ness")) { r(""); break; }
break;
} }
/* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */
private final void step5()
{ if (k == 0) return; /* for Bug 1 */ switch (b[k-1])
{ case 'a': if (ends("al")) break; return;
case 'c': if (ends("ance")) break;
if (ends("ence")) break; return;
case 'e': if (ends("er")) break; return;
case 'i': if (ends("ic")) break; return;
case 'l': if (ends("able")) break;
if (ends("ible")) break; return;
case 'n': if (ends("ant")) break;
if (ends("ement")) break;
if (ends("ment")) break;
/* element etc. not stripped before the m */
if (ends("ent")) break; return;
case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break;
/* j >= 0 fixes Bug 2 */
if (ends("ou")) break; return;
/* takes care of -ous */
case 's': if (ends("ism")) break; return;
case 't': if (ends("ate")) break;
if (ends("iti")) break; return;
case 'u': if (ends("ous")) break; return;
case 'v': if (ends("ive")) break; return;
case 'z': if (ends("ize")) break; return;
default: return;
}
if (m() > 1) k = j;
}
/* step6() removes a final -e if m() > 1. */
private final void step6()
{ j = k;
if (b[k] == 'e')
{ int a = m();
if (a > 1 || a == 1 && !cvc(k-1)) k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1) k--;
}
/** Stem the word placed into the Stemmer buffer through calls to add().
* Returns true if the stemming process resulted in a word different
* from the input. You can retrieve the result with
* getResultLength()/getResultBuffer() or toString().
*/
public void stem()
{
// step1();
// System.out.println("hello in stem");
// step2();
// step3();
// step4();
// step5();
// step6();
//
// i_end = k+1;
// i = 0;
System.out.println(i);
k = i - 1;
if (k > 1)
{
step1();
step2();
step3();
step4();
step5();
step6();
}
for(int c=0;c<=k;c++)
System.out.println(b[c]);
i_end = k+1; i = 0;
}
public static void main(String[] args)
{
stemmer s = new stemmer();
s.addstring("looking");
s.stem();
s.addstring("walks");
s.stem();
//System.out.println("Output " +s.b);
}
}
- Use Character class method toString();
Eg:
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
char c = 'a';
String s = Character.toString(c);
System.out.println(s);
}
}
- Now use this above explained method to convert all the character array items into String.
char[] data = new char[10];
String text = String.valueOf(data);
to convert a char[] to string use this way
String x=new String(char[])
example
char x[]={'a','m'};
String z=new String(x);
System.out.println(z);
output
am
char[] a = new char[10];
for(int i=0;i<10;i++)
{
a[i] = 's';
}
System.out.println(new String(a));
or
System.out.println(String.copyValueOf(a));

Categories

Resources