Skipping one value when storing into an array [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Can someone help me check ?
error:
java.lang.NullPointerException
How do I remove this error ?
my main Class:
public class deck {
public static void main(String[] args) {
Deck app = new Deck();
app.Deck();
}
}
my Deck class:
public class Deck {
public int TOTALCARDS;
Card[] d;
public int nH;
public void createDeck() {
String[] suitsArray = new String[4];
for(int i=0; i<numArray.length; i++) {
numArray[i] = i+1;
}
for (int i=0; i<13; i++) {
if (i!=11){
deck[i+25] = new Card(suitsArray[2], i+1);
}
else if(i > 10){
deck[i+25] = new Card(suitsArray[2], i+1);
}
}
for (int i=0; i<13; i++) {
deck[i+25].display();
}
}
This is the Card Class.
public class Card {
public String suit;
public int number;
public Card(String s, int n){
this.suit = s;
this.number = n;
}
public String words;
public String getTitle(){
String
if (number == 1){
words = " Ace";
}
else if (number ==3){
words = " Three";
}
else if (number ==4){
words = " Four";
}
else if (number ==5){
words = " Five";
}
else if (number ==6){
words = " Six";
}
else if (number ==7){
words = " Seven";
}
else if (number ==8){
words = " Eight";
}
else if (number ==9){
words = " Nine";
}
else if (number ==10){
words = " Ten";
}
else if (number ==11){
words = " Jack";
}
else if (number ==12){
words = " Queen";
}
else if (number ==13){
words = " King";
}
displayTitle = suit + words;
if (displayTitle.equalsIgnoreCase("Diamond Queen")){
displayTitle= "DIAMOND QUEEN";
}
return (displayTitle);
}
public void display(){
System.out.println("< " + get() + " >");
}
}
When I run the code I got
Hearts Ace
Hearts Two
Hearts Three
Hearts Four
Hearts Five
Hearts Six
Hearts Seven
Hearts Eight
Hearts Nine
Hearts Ten
Hearts Jack
Exception in thread "main" java.lang.NullPointerException
at Deck.createDeck(Deck.java:57)
at Deck.<init>(Deck.java:9)
at deckMain.main(deckMain.java:5)

EDIT: See the comment by Kick Buttowski below, this is at best a partial answer.
You're calling Card.display()
for (int i=0; i<13; i++) {
deck[i+25].display();
}
Which in turn calls Card.getTitle()
public void display(){
System.out.println("< " + getTitle() + " >");
}
The problem lies there:
public String getTitle(){
String displayTitle = suit + words; // <-- Problem
if (number == 1){
words = " Ace";
}
// ...
At the marked line, words is not set yet, so it's null. Accessing its value will raise a NullPointerException.
As Takendarkk pointed out, you can overcome this with minimal changes to your code by initialising it either in your constructor or in the declaration:
public class Card {
// ...
String words = "";
Or, since (as far as we know) words is only used within display(), move it there:
public void display() {
String words = ""; // Still need to be initialised
// ...

EDIT: Your card size is 51 ... it should be 52
if (i!=11){
deck[i+25] = new Card(suitsArray[2], i+1);
}
else if(i > 11){
deck[i+25] = new Card(suitsArray[2], i+1);
}
This doesn't add up, what if i = 11?? You do nothing as
i!=11 = false and i > 11 == false;
this means the else if (i > 11) will never execute.
also your code does the exact same thing??
if you are trying to initalise all 52 cards you can do something like:
for (int i=0;i<deck.size;i++) {
deck[i] = new Card(suitsArray[i/13], numArray[i % 13]);
EDIT: after more of an explanation of what you are doing .....
for (int i=0, j=0;j<deck.length;i++) {
if ((i/13) == 2 && (i%13) == 11)
continue;
deck[j++] = new Card( suitsArray[i/13], (i % 13));
}
also in card have (much clearer)
static String[] titles = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
and
public String getTitle() {
return suit + " " + titles[number];
}

It is because your value at deck[11] is null because you skipped putting an instance of Card at that index.
edit: [should be deck[i + 25]], where i = 11;
Regarding the answers pointing to the variable word being null as reason of NPE. I doubt this. I have tried the code in my machine and it is not giving me NPE. (see also Concatenating null strings in Java)

Related

Is there any way to count integer elements in text file?

So I have a text file as :
and I want to count the number of integers in the first row.
// e.g. The first row : 3 12 1 8 5 8 1 2 1 4 --> 10
Can I do that with a stream or for statement or another way?
I tried with for and it didn't work for me and I couldn't find any useful solution. Please, help me.
public class Egyszamjatek {
public static void main(String[] args) throws IOException {
List<String> game = Files.readAllLines(Paths.get("egyszamjatek.txt"));
ArrayList<OneGame> games = new ArrayList<>();
for (String game1 : game) {
String[] split = game1.split(" ");
int rounds = Integer.parseInt(split[0]) + Integer.parseInt(split[1]) + Integer.parseInt(split[2])
+ Integer.parseInt(split[3]) + Integer.parseInt(split[4]) + Integer.parseInt(split[5])
+ Integer.parseInt(split[6]) + Integer.parseInt(split[7]) + Integer.parseInt(split[8])
+ Integer.parseInt(split[9]);
String names = split[10];
games.add(new OneGame(rounds, names));
}
System.out.println("3.feladat: number of players : " + game.stream().count());
System.out.println("4. feladat: number of rounds: " );
}
static class OneGame {
int rounds;
String names;
public OneGame(int rounds, String names) {
this.rounds = rounds;
this.names = names;
}
}
}
solution with for loop
String firstLine = "3 12 1 8 5 8 1 2 1 4";
String[] splits = firstLine.split(" ");
int count = 0 ;
for(String intStr:splits){
try {
int i = Integer.parseInt(intStr);
count++;
}catch (NumberFormatException e){
e.printStackTrace();
}
}
System.out.println(count);
You could do something like:
List<OneGame> games = Files.lines(Paths.get("egyszamjatek.txt")) // Stream<String> each line as a single String
.map(g -> {
String[] split = g.split(" ");
int rounds = (int) Arrays.stream(split)
.filter(a -> isInteger(a)) // filter only integers
.count(); // count how many integers e.g. 10 in your first line
return new OneGame(rounds, split[rounds]); // create an instance with count and name
}).collect(Collectors.toList()); // collect to list
where isInteger(a) is a util that you can use from this answer. Its implementation would be :
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
if (str.isEmpty()) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (str.length() == 1) {
return false;
}
i = 1;
}
for (; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
Note: the code relies on certain assumptions for e.g. the integer values for the number of rounds would supersede the name of the game and hence uses split[rounds] to access the name.

Deck of Cards - checking for a straight

I've made this poker program. It evaluates the hand and returns the results.
Everything works except my method to check for a straight. There is no error, but the method never returns true.
As a test, I have a while loop on the main (DeckOfCardsTest) to rerun the program until a straight is found.
Here is the code:
public class DeckOfCardsTest {
public static Card[] hand = new Card[5];
public static void main(String[] args) {
while(DeckOfCards.str == 0){
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle(); // place Cards in random order
// print the hand dealt
for (int i = 0; i < 5; i++) {
// deal and display a Card
//System.out.printf("%-19s%n", myDeckOfCards.dealCard());
hand[i]= myDeckOfCards.dealCard();
if (i % 5 == 0) { // output a newline after every fifth card, incase dealing 2 hands in the future
System.out.println();
}
}//end of for loop
for(int i = 0; i < hand.length; i++){
System.out.println(""+ hand[i]);
}
DeckOfCards.Pair();//check hand for pair, 2 pair, 3 of a kind, four of a kind, or a full house
DeckOfCards.hasFlush(hand);//check hand for flush
System.out.println("\n\n\t" + DeckOfCards.Results() + "\n\n " + DeckOfCards.str);
//System.out.println(""+DeckOfCards.hasStraight(hand));
DeckOfCards.flushn=0;
}
} //end of main
}//end of class
Card Class
public class Card {
private final String face; // face of card ("Ace", "Deuce", ...)
private final String suit; // suit of card ("Hearts", "Diamonds", ...)
// two-argument constructor initializes card's face and suit
public Card(String cardFace, String cardSuit) {
this.face = cardFace; // initialize face of card
this.suit = cardSuit; // initialize suit of card
} //end of Card inilization
// return String representation of Card
public String toString() {
return face + " of " + suit;
}// endof toString method
public String getFace() {
return face;
}//end of getFace method
public String getSuit() {
return suit;
}//end of getSuit method
}//end of Class
Deck class
import java.security.SecureRandom;
public class DeckOfCards {
// random number generator
private static final SecureRandom randomNumbers = new SecureRandom();
private static final int NUMBER_OF_CARDS = 52; // constant # of Cards
public static int flushn = 0;
public static int str=0;
//private Card[] hand;
private Card[] deck = new Card[NUMBER_OF_CARDS]; // Card references
private int currentCard = 0; // index of next Card to be dealt (0-51)
// constructor fills deck of Cards
public DeckOfCards() {
String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};
// populate deck with Card objects
for (int count = 0; count < deck.length; count++) {
deck[count] =
new Card(faces[count % 13], suits[count / 13]);
}
} //end of DeckOfCards constructor
public String getCard(){
String cCard = ("");
return cCard;
}
// shuffle deck of Cards with one-pass algorithm
public void shuffle() {
// next call to method dealCard should start at deck[0] again
currentCard = 0;
// for each Card, pick another random Card (0-51) and swap them
for (int first = 0; first < deck.length; first++) {
// select a random number between 0 and 51
int second = randomNumbers.nextInt(NUMBER_OF_CARDS);
// swap current Card with randomly selected Card
Card temp = deck[first];
deck[first] = deck[second];
deck[second] = temp;
}
} //end of shuffle method
// deal one Card
public Card dealCard() {
// determine whether Cards remain to be dealt
if (currentCard < deck.length) {
return deck[currentCard++]; // return current Card in array
}
else {
return null; // return null to indicate that all Cards were dealt
}
}//end of dealCard method
public static void hasFlush(Card[] hand) {
boolean isFlush = true;
String suit = hand[0].getSuit();
for(int i = 1; i < hand.length; i++) {
if(!(hand[i].getSuit().equals(suit))) {
isFlush = false;
}
}
if(isFlush){
flushn = 5;
}
}//end of flush evaluation
public static boolean hasStraight(Card[] hand) {
String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
int minFace = 13;
for(int i = 0; i < hand.length; i++) {
int face = 13;
for(int j = 0; j < faces.length; j++) {
if(hand[i].getFace().equals(faces[j])) {
face = j;
}
}
if(face < minFace) {
minFace = face;
}
}
if(minFace > 7) {
return false;
}
boolean isStraight = true;
for(int i = minFace+1; i < minFace+hand.length; i++) {
boolean found = false;
for(int j = 0; j < hand.length; j++) {
if(hand[j].getFace().equals(faces[i])) {
found = true;
str++;
}
}
if(!found) {
str=0;
isStraight = false;
}
}
return isStraight;
}
public static int Pair(){
int pair = 0, done = 0, handcount = 1;
int pairCheck=0;
while (done <1){
for(int i = 0; i < 4; i++){
String tempCard = DeckOfCardsTest.hand[i].getFace();
for(int j=handcount; j < DeckOfCardsTest.hand.length; j++){
if(tempCard.equals(DeckOfCardsTest.hand[j].getFace()))
pair++;
}
handcount++;
}
pairCheck = pair;
done++;
}
return pairCheck;
}//endof Pair method
public static String Results(){
String results=("High Card");
int checkHand = 0;
if (Pair()>0 ){
switch (Pair()){
case 1:
results = ("Pair");
break;
case 2:
results = ("Two Pair!");
break;
case 3:
results = ("Three of a kind!");
break;
case 4:
results = ("Full House!");
break;
case 6:
results = ("FOUR of a kind!");
break;
default:
results = ("Somthing went terribly wrong, sorry");
break;
}
}//end of pairing results
if (flushn > 0){
results = ("Flush!");
}
if (str > 0){
results = ("Straight!");
}
return results;
}
}//end of Class
There is no error, but the method never returns true
This is not true. Your current hasStraight method is almost correct and does in fact return true/false correctly. The main issue you have is that your main loop uses the static variable str. There is a bug which does not reset str to zero correctly.
In short, there are two ways to address your problem:
1) Fix the issue with str
if (!found) {
str = 0;
isStraight = false;
break;
}
2) The main loop should use the boolean result of hasStraight instead of str.
boolean b = false;
while (!b) {
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle(); // place Cards in random order
// print the hand dealt
for (int i = 0; i < 5; i++) {
// deal and display a Card
// System.out.printf("%-19s%n", myDeckOfCards.dealCard());
hand[i] = myDeckOfCards.dealCard();
if (i % 5 == 0) { // output a newline after every fifth card,
// incase dealing 2 hands in the future
System.out.println();
}
} // end of for loop
for (int i = 0; i < hand.length; i++) {
System.out.println("" + hand[i]);
}
DeckOfCards.Pair();// check hand for pair, 2 pair, 3 of a kind, four
// of a kind, or a full house
DeckOfCards.hasFlush(hand);// check hand for flush
System.out.println("\n\n\t" + DeckOfCards.Results() + "\n\n " + DeckOfCards.str);
b = DeckOfCards.hasStraight(hand);
System.out.println("Straight= " + b);
DeckOfCards.flushn = 0;
}
If I use either of these fixes, the main loop will loop until there is a straight.
Notes:
1. I believe the minFace check should be:
if (minFace > 8) {
return false;
}
Can an ace be high?
Ace code?
boolean hasAce = false;
for (int i = 0; i < hand.length; i++) {
if (hand[i].getFace().equals("Ace"))
hasAce = true;
}
// ... Current code ....
if (!isStraight && hasAce) {
isStraight = true;
for (int i = 9; i < 13; i++) {
boolean found = false;
for (int j = 0; j < hand.length; j++) {
if (hand[j].getFace().equals(faces[i])) {
found = true;
str++;
}
}
if (!found) {
str = 0;
isStraight = false;
break;
}
}
}
return isStraight;

Poker game hand evaluator arrays condition structure

I made up a quick poker game. It generates 5 random numbers and converts those numbers into actual cards values and symbols based on their value. However, I have problems when it comes to making the hand evaluation.
So far I only did the flush right as it's really easy but even then it's not perfect (it prints that the user has a flush 5 times... ) and I would really appreciate if someone could help me with the pair, two pair, three of a kind and straight. I could do the rest afterwards but I just need a heads-up on how to do those.
Thank you in advance for your help, here is the code :
package tests;
import java.util.*;
public class TESTS {
public static void main(String[] args) {
boolean[] pack = new boolean[52]; // Array to not generate the same number twice
int[] cards = new int[5]; //The 5 unique random numbers are stored in here.
String[] cardsvalues = new String[5]; // This will assign the card's value based on the random number's value
char[] cardssymbols = new char[5];//This will assign the card's symbol based on the random number's value
char symbols[] = {'♥', '♦', '♣', '♠'}; // possible symbols that the random number can take
String values[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; // possible values that the random number can take
Random give = new Random();
for (int i = 0; i < cards.length; i++) { // Gives 5 unique random numbers
do {
cards[i] = give.nextInt(52);
} while (pack[cards[i]]);
pack[cards[i]] = true;
System.out.println(cards[i]);
}
for (int i = 0; i < cards.length; i++) { // This converts the number to a card symbol based on the number's value
final int numOfSymbol = cards[i] / 13;
cardssymbols[i] = symbols[numOfSymbol];
}
for (int i = 0; i < cards.length; i++) { // This converts the number to an actual card value based on the number's value.
final int numOfValues = cards[i] % 13;
cardsvalues[i] = values[numOfValues];
}
for (int i = 0; i < cardssymbols.length; i++) { // Prints the actual cards once they are converted
System.out.print(cardssymbols[i]);
System.out.println(cardsvalues[i]);
}
for (int i = 0; i < cardsvalues.length; i++) { //Here is the problem, i have no idea on how to make the handevaluator ...
if (cardsvalues[i] == cardsvalues[i] + 1) {
System.out.println("PAIR !!!");
} else if (cardsvalues[i] == cardsvalues[i] + 1 && cardsvalues[i] == cardsvalues[i] + 2) {
System.out.println("TRIPS !!!");
} else if (cardssymbols[0] == cardssymbols[1] && cardssymbols[1] == cardssymbols[2] && cardssymbols[2] == cardssymbols[3] && cardssymbols[3] == cardssymbols[4]) {
System.out.println("FLUSHHH");
}
}
}
Hints:
To simplify testing for straights and sorting by highest card, it is easier to represent ranks by their indexes, and only translate them to the symbols for printing.
Using a Card object allows for clearer code.
The Java Collection framework has useful functions for shuffling, slicing and sorting.
My solution:
public class Test {
static final char[] suits = {'♥', '♦', '♣', '♠'};
static final String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
static class Card {
final int suit;
final int rank;
Card(int s, int r) {
suit = s;
rank = r;
}
#Override
public String toString() {
return suits[suit] + ranks[rank]; // or however you want the cards to be printed
}
}
public static void main(String[] args) {
List<Card> deck = new ArrayList<>();
for (int s = 0; s < suits.length; s++) {
for (int r = 0; r < ranks.length; r++) {
deck.add(new Card(s,r));
}
}
Collections.shuffle(deck);
List<Card> hand = deck.subList(0,5);
Collections.sort(hand, Comparator.comparing(c -> c.rank));
System.out.println("Your hand is: " + hand);
System.out.println(value(hand));
}
static String value(List<Card> hand) {
boolean straight = true;
boolean flush = true;
for (int i = 1; i < hand.size(); i++) {
straight &= hand.get(i - 1).rank + 1 == hand.get(i).rank;
flush &= hand.get(i - 1).suit == hand.get(i).suit;
}
if (straight && flush) {
return "Straight Flush from " + hand.get(4);
}
List<Run> runs = findRuns(hand);
runs.sort(Comparator.comparing(r -> -r.rank));
runs.sort(Comparator.comparing(r -> -r.length));
if (runs.get(0).length == 4) {
return "Four of a Kind: " + runs;
}
if (runs.get(0).length == 3 && runs.get(1).length == 2) {
return "Full House: " + runs;
}
if (straight) {
return "Straight from " + hand.get(4);
}
if (runs.get(0).length == 3) {
return "Three of a Kind: " + runs;
}
if (runs.get(1).length == 2) {
return "Two pair: " + runs;
}
if (runs.get(0).length == 2) {
return "Pair: " + runs;
}
return "High card: " + runs;
}
/** Represents {#code length} cards of rank {#code rank} */
static class Run {
int length;
int rank;
#Override
public String toString() {
return ranks[rank];
}
}
static List<Run> findRuns(List<Card> hand) {
List<Run> runs = new ArrayList<>();
Run run = null;
for (Card c : hand) {
if (run != null && run.rank == c.rank) {
run.length++;
} else {
run = new Run();
runs.add(run);
run.rank = c.rank;
run.length = 1;
}
}
return runs;
}
}
Example output:
Your hand is: [♣10, ♥J, ♦J, ♠K, ♥K]
Two pair: [K, J, 10]

Disappearing Arraylist Values

I am writing a Java program that will take a sentence (or phrase) and translate it into a group of objects that the computer can easily read. I wanted to make a simple word separating program, and then extend it later on.
My code is like this:
package Literary;
import java.util.ArrayList;
public class WordParser {
public static String[] getWords(String tempone){
ArrayList<String> temptwo = new ArrayList();
ArrayList<Character> tempthree = new ArrayList();
for (int tempfour = 0; tempfour == tempone.length() - 1; tempfour++){
if (tempone.charAt(tempfour) != ' '){
tempthree.add(tempone.charAt(tempfour));
} else {
temptwo.add(getStringRepresentation(tempthree));
tempthree.clear();
}
}
String[] tempfive = new String[temptwo.size()];
for (int tempfour = 0; tempfour == tempfive.length - 1; tempfour++){
tempfive[tempfour] = temptwo.get(tempfour);
}
return tempfive;
}
/** Courtesy of Vineet Reynolds on StackExchange.
*
* "You can iterate through the list and create the string."
*
* #param list
* #return
*/
public static String getStringRepresentation(ArrayList<Character> list){
StringBuilder builder = new StringBuilder(list.size());
for(int i = 0; i == list.size() + 1; i++)
{
builder.append(list.get(i).charValue());
}
return builder.toString();
}
}
It's supposed to receive a string as an input, and return a list of strings that have been separated by spaces.
But when I run my main class:
import Literary.WordParser;
public class Start {
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 1; i == tempstring.length; i++){
System.out.println("Word " + i + " : " + tempstring[i]);
}
}
}
The console tells me nothing except run: and BUILD SUCCESSFUL (total time: 1 second).
I'm using Netbeans 8 and Java 1.7 if that helps.
Looks like the problem's here:
for (int i = 1; i == tempstring.length; i++) {
This for loop will run at most once: if tempstring is exactly one String long, it should print out the word.
However, since your test sentence has 8 words, nothing will ever print out (provided WordParser works correctly).
You probably want to change this line to: (note the < between i and tempstring.length.)
for (int i = 1; i < tempstring.length; i++) {
so that it will loop through all the items in tempstring.
You had multiple issues in your code:
1) for loops were not properly made, they would never execute. Use either !=, > or < instead of ==.
2) you don't need a method getWords() nor getStringRepresentation(). Method like that are already implemented in Java.
So the final code should be this:
public class WordParser {
public static String[] getWords(String tempone) {
return tempone.split(" ");
}
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 0; i < tempstring.length; i++) {
System.out.println("Word " + (i+1) + " : " + tempstring[i]);
}
}
}
Output:
Word 1 : There
Word 2 : was
Word 3 : once
Word 4 : a
Word 5 : sword
Word 6 : in
Word 7 : the
Word 8 : stone
I've also fixed your code that runs the same as above, if you are interested:
import java.util.ArrayList;
public class WordParser {
public static String[] getWords(String tempone) {
ArrayList<String> sarr = new ArrayList<String>();
ArrayList<Character> tempthree = new ArrayList<Character>();
String[] ansarr;
if(tempone.charAt(tempone.length()-1) != ' ')
tempone += " "; //Add white space to the end to catch the last word
for (int i = 0; i < tempone.length(); i++) {
if (tempone.charAt(i) != ' ') {
tempthree.add(tempone.charAt(i));
} else {
sarr.add(tempthree.toString());
tempthree.clear();
}
}
ansarr = new String[sarr.size()];
for (int i = 0; i < ansarr.length; i++) {
ansarr[i] = sarr.get(i);
}
return ansarr;
}
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 0; i < tempstring.length; i++) {
System.out.println("Word " + (i+1) + " : " + tempstring[i]);
}
}
}
Enjoy! :)
I think you should use String.split(" ") which seems to do the same thing
Change your main method as follows,
and it will work
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 1; i <= tempstring.length; i++){
System.out.println("Word " + i + " : " + tempstring[i - 1]);
}
}
For the WordParser you could use,
public class WordParser
{
public static String[] getWords(String tempone)
{
return tempone.split(" ");
}
}
First of, I would recommend using the split method to break up a sentence
it is defined as:
public String[] split(String regex, int limit)
and you can simply call
String s1=new String("Random words in a sentence");
String[] words=s1.split(" ");
in order to break the string up into words and you will now have a String
array of five elements where each element consists of a word
In Respect to your question, you are not using the conditional statement correctly
You want to iterate over the elements of the String array WHILE the position
is less than stringname.length, not only if it the position equals the stringname.length
Therefore, you must make the following changes in these parts of your code
For Example:
for (int i = 1; i == tempstring.length; i++)
should have its line changed to
for (int i = 1; i < tempstring.length; i++)
and this problem also occurs in various places in your WordParser.java file
It is useful to remember also that you may often want to start at index 0 instead
of index 1, as java has its' first indice as 0.

Arraylist of objects to Array of strings

I'm trying to convert an ArrayList that contains "cards", or objects that store two numbers, a rank and a suit. Normally to get a single instance of the card, I use:
dealer.dealerhand.get(1).showstats();
Where showstats returns a string and is:
public String showstats()
{
String realsuit = "";
if(this.suit == 0)
{
realsuit = "Diamonds";
}
else if(this.suit == 1)
{
realsuit ="Hearts";
}
else if(this.suit == 2)
{
realsuit = "Clubs";
}
else if(this.suit == 3)
{
realsuit = "Spades";
}
String str = "My rank is: " + this.rank + " My Suit is: " + realsuit;
return str;
}
What I've tried so far is:
public String[] getStats()
{
String[] dealerstats = this.dealerhand.toArray(new String[this.dealerhand.size()]);
return dealerstats;
}
and
public String[] getStats()
{
String[] dealerstats = {""};
for(int i = 0; i < this.dealerhand.size(); i++)
{
dealerstats[i] = (dealerhand.get(i).showstats());
}
return dealerstats;
}
But they both don't work. The end goal would be a string array of the cards in the dealerhand ArrayList, that I will print out using JList. Thanks!
For this:
public String[] getStats() {
for(int i = 0; i < this.dealerhand.size(); i++) {
dealerstats[i] = (dealerhand.get(i).showstats());
}
return dealerstats;
}
make sure to initialize your String array, such as below:
public String[] getStats(Dealer dealer) { // Input a dealer
String[] dealerstats = new String[dealer.dealerhand.size()]; // Initialize String array
for(int i = 0; i < this.dealerhand.size(); i++) {
dealerstats[i] = dealerhand.get(i).showstats();
}
return dealerstats;
}
I am also assuming you have a Dealer object, as you seem to reference one in your question.
Your second attempt is almost correct. You created the array but without giving it the correct size. The String[] dealerstats size should be the size of the ArrayList dealerhand:
public String[] getStats()
{
String[] dealerstats = new String[ dealerhand.size() ];
for( int i = 0; i < dealerstats.length; ++i )
dealerstats[i] = dealerhand.get(i).showstats();
return dealerstats;
}
If you define a toString() method in your Card class you can print the ArrayList out without any conversion (Live Ideone Example here):
public class Card{
...
#Override public String toString(){
return "My rank is: " + this.rank + " My Suit is: " + this.suit;
}
}
Then you can just use:
List<Card> dealerCards = new ArrayList<Card>();
dealerCards.add(new Card(5, "Hearts"));
dealerCards.add(new Card(10, "Diamonds"));
System.out.println(dealerCards);
Output: ["My rank is: 5 My Suit is: Hearts", "My rank is: 10 My Suit is: Diamonds"]

Categories