My two functions isSorted and hasDuplicate created below should work, right? My test class for the assignment wasn't working. The instructions for both are in the comments below. isSorted returns true if the string array is sorted alphabetically, and false - if not. hasDuplicate returns true if there's at least one set of duplicate strings and false - if not.
public class CheckStrings {
/**
* Returns true if the Strings in w appear in sorted order
* (alphabetical order) and false otherwise.
*
* #param w the array of Strings to check
* #return true if the Strings in w appear in sorted order
* and false otherwise.
*/
public static boolean isSorted(String[] w) {
boolean bob = true;
for (int i = 0; i < w.length-1; i++)
{
if (w[i].compareTo(w[i+1]) >= 0)
{
bob = true;
}
else
{
bob = false;
i = w.length + 50;
}
}
return bob;
}
/**
* Returns true if at least one String in w appears more than once
* and false otherwise.
*
* #param w the array of Strings to check
* #return true if at least one String in w appears more than once
* and false otherwise.
*/
public static boolean hasDuplicate(String[] w) {
boolean bob = true;
for (int i = 0; i < w.length-1; i++)
{
if (w[i].equals(w[i+1]))
{
bob = true;
i = w.length + 50;
}
else
{
bob = false;
}
}
return bob;
}
}
Submit this for your homework:
public static boolean isSorted(String[] w) {
return Arrays.stream(w).reduce("",(a, b) -> a == null || a.compareTo(b) > 0 ? null : b) != null;
}
public static boolean hasDuplicate(String[] w) {
return Arrays.stream(w).distinct().count() == w.length;
}
And who is Bob?
In case you're not allowed yet to use Java 8 Stream API, implementation of the isSorted and hasDuplicate may look as follows:
public static boolean isSorted(String[] w) {
if (null == w || w.length == 0) {
return false;
}
for (int i = 0; i < w.length-1; i++) {
if (w[i].compareTo(w[i+1]) > 0) { // or compareToIgnoreCase if case insensitive is ok
return false;
}
}
return true;
}
public static boolean hasDuplicate(String[] w) {
if (null == w || w.length < 2) return false;
Set<String> set = new HashSet<>();
for (int i = 0; i < w.length-1; i++) {
String s = w[i]; // if case-insensitive lookup needed use s = w[i].toLowerCase();
if (set.contains(s)) {
return true;
}
set.add(s);
}
return false;
}
public final class CheckStrings {
private CheckStrings() {
}
public static boolean isSorted(String... w) {
if (w == null || w.length == 0)
return false;
for (int i = 0, j = w.length - 1; j < w.length; i++, j++)
if (w[i].compareToIgnoreCase(w[j]) > 0)
return false;
return true;
}
public static boolean hasDuplicate(String... w) {
if (w == null || w.length == 0)
return false;
Set<String> unique = new HashSet<>();
for (String str : w)
if (!unique.add(str.toLowerCase()))
return false;
return true;
}
}
Output:
String[] arr = {"a", "a", "b", "b", "c", "c"};
System.out.println(CheckStrings.isSorted(arr)); // true
System.out.println(CheckStrings.hasDuplicate(arr)); // true
Prompt: Write a program that reads five cards from the user, then analyzes the cards and prints out the category of hand that they represent.
Poker hands are categorized according to the following labels: Straight flush, four of a kind, full house, flush, straight, three of a kind, two pairs, pair, high card.
I currently have my program set as follows, first prompting the user for 5 cards, 2-9, then sorting the cards in ascending order. I set up my program to prompt the user and then go through several if else statements calling methods. I am having issues though where its not identifying three or four of a kind.
Example, if I enter 1, 3, 2, 1, 1, it identifies it as TWO PAIRS instead of Three of a Kind.
Same for entering 1, 1,1, 1, 4, it identifies as three of kind instead of 4.
Any suggestions to my code?
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int HAND_SIZE = 5;
int[] hand = new int[HAND_SIZE];
getHand(hand); //Prompt user for hand
sortHand(hand);//Sort hand in ascending order
if(containsFullHouse(hand))
{
System.out.print("FULL HOUSE!");
}
else if(containsStraight(hand))
{
System.out.print("STRAIGHT!");
}
else if(containsFourOfAKind(hand))
{
System.out.print("FOUR OF A KIND!");
}
else if(containsThreeOfAKind(hand))
{
System.out.println("THREE OF A KIND!");
}
else if(containsTwoPair(hand))
{
System.out.println("TWO PAIRS!");
}
else if(containsPair(hand))
{
System.out.println("PAIR!");
}
else
System.out.println("High Card!");
}
public static void getHand(int[] hand)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter five numeric cards, 2-9, no face cards please");
for(int index = 0; index < hand.length; index++)
{
System.out.print("Card " + (index + 1) + ": ");
hand[index] = input.nextInt();
}
}
public static void sortHand(int[] hand)
{
int startScan, index, minIndex, minValue;
for(startScan = 0; startScan < (hand.length-1); startScan++)
{
minIndex = startScan;
minValue = hand[startScan];
for(index = startScan + 1; index <hand.length; index++)
{
if(hand[index] < minValue)
{
minValue = hand[index];
minIndex = index;
}
}
hand[minIndex] = hand[startScan];
hand[startScan] = minValue;
}
}
public static boolean containsPair(int hand[])
{
boolean pairFound = false;
int pairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
pairCount++;
}
startCheck = hand[index];
}
if (pairCount == 1)
{
pairFound = true;
}
else if(pairCount !=1)
{
pairFound = false;
}
return pairFound;
}
public static boolean containsTwoPair(int hand[])
{
boolean twoPairFound = false;
int twoPairCount = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
twoPairCount++;
}
startCheck = hand[index];
}
if (twoPairCount == 2)
{
twoPairFound = true;
}
else if(twoPairCount != 2)
{
twoPairFound = false;
}
return twoPairFound;
}
public static boolean containsThreeOfAKind(int hand[])
{
boolean threeFound = false;
int threeKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
threeKind++;
}
startCheck = hand[index];
}
if(threeKind == 3)
{
threeFound = true;
}
else if(threeKind !=3)
{
threeFound = false;
}
return threeFound;
}
public static boolean containsStraight(int hand[])
{
boolean straightFound = false;
int straight = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 1)
{
straight++;
}
startCheck = hand[index];
}
if(straight == 4)
{
straightFound = true;
}
return straightFound;
}
public static boolean containsFullHouse(int hand[])
{
boolean fullHouseFound = false;
int pairCheck = 0;
int startPairCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startPairCheck) == 0)
{
pairCheck++;
}
startPairCheck = hand[index];
}
int threeOfKindCheck = 0;
int startThreeKindCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startThreeKindCheck) == 0)
{
threeOfKindCheck++;
}
startThreeKindCheck = hand[index];
}
if(pairCheck == 1 && startThreeKindCheck == 3)
{
fullHouseFound = true;
}
return fullHouseFound;
}
public static boolean containsFourOfAKind(int hand[])
{
boolean fourFound = false;
int fourKind = 0;
int startCheck = hand[0];
for(int index = 1; index < hand.length; index++)
{
if((hand[index] - startCheck) == 0)
{
fourKind++;
}
startCheck = hand[index];
}
if(fourKind == 1)
{
fourFound = true;
}
else if(fourKind !=4)
{
fourFound = false;
}
return fourFound;
}
}
Some hints.
Start with the highest hand. This eliminates lots of logic.
I.e if you check for pairs first, than you also have to check to make sure that your pair is the only pair, and not three of a kind.
But if you already ruled all of those out your code would be check card 1and2 23 34 and 45.
My code below is supposed to sort version numbers into proper order. For the most part it works, but it fails a hidden test case that I don't have access to. Given that is there any edge case you can see that I might be missing.
import java.util.*;
public class Answer {
public static void main(String[] args)
{
//Testing
String[] versions = {"0.0.0","0","0.0","1.113","0.0.0.1","2.0.0","1.2","2","0.1","1.2.1","1.1.1","2.0"};
String[] results = answer(versions);
for(int i =0; i<results.length;i++)
{
System.out.println(results[i]);
}
}
public static String[] answer(String[] l) {
String temp = new String();
//Insertion sort on the given array to assign correct version numbers
for (int i = 1; i < l.length; i++) {
for(int j = i ; j > 0 ; j--){
if(compareVersion(l[j],l[j-1])<0){
temp = l[j];
l[j] = l[j-1];
l[j-1] = temp;
}
}
}
return l;
}
//Will compare version numbers breaking it apart into a String array
public static int compareVersion(String version1, String version2) {
String[] arr1 = version1.split("\\.");
String[] arr2 = version2.split("\\.");
int i=0;
while(i<arr1.length || i<arr2.length){
if(i<arr1.length && i<arr2.length){
if(Integer.parseInt(arr1[i]) < Integer.parseInt(arr2[i])){
return -1;
}else if(Integer.parseInt(arr1[i]) > Integer.parseInt(arr2[i])){
return 1;
}
else if(Integer.parseInt(arr1[i]) == Integer.parseInt(arr2[i]))
{
int result = specialCompare(version1,version2);
if(result != 0)
{
return result;
}
}
} else if(i<arr1.length){
if(Integer.parseInt(arr1[i]) != 0){
return 1;
}
} else if(i<arr2.length){
if(Integer.parseInt(arr2[i]) != 0){
return -1;
}
}
i++;
}
return 0;
}
// Meant for when version numbers such as 2 and 2.0 arise. This method will make sure to
// put the smaller version number ( in length) first
public static int specialCompare(String str1, String str2)
{
String[] arr1 = str1.split("\\.");
String[] arr2 = str2.split("\\.");
for(int i =1; i<arr1.length;i++)
{
if(Integer.parseInt(arr1[i]) != 0)
{
return 0;
}
}
for(int j =1; j<arr2.length;j++)
{
if(Integer.parseInt(arr2[j]) != 0)
{
return 0;
}
}
if(arr1.length < arr2.length)
{
return -1;
}
else
{
return 1;
}
}
}
I read Lukas Eder's blog post in the comment above and created a java.util.Comparator which orders by version (or chapter) number, based on a JDK proposal.
VersionNumberComparator is defined in a GitHub gist. The follow code shows how it works.
import java.util.ArrayList;
import java.util.List;
public class JavaTest {
public static void main(String[] args) {
final List<String> chapters = new ArrayList<>();
chapters.add("1.1");
chapters.add("1.2");
chapters.add("1");
chapters.add("1.3");
chapters.add("1.1.1");
chapters.add("5.6");
chapters.add("1.1.10");
chapters.add("4");
chapters.add("1.1.9");
chapters.add("1.2.1.10");
chapters.add("2.1.1.4.5");
chapters.add("1.2.1.9");
chapters.add("1.2.1");
chapters.add("2.2.2");
chapters.add("1.2.1.11");
System.out.println("UNSORTED: " + chapters.toString());
chapters.sort(VersionNumberComparator.getInstance());
System.out.println("SORTED: " + chapters.toString());
}
}
Produces the following output:
UNSORTED: [1.1, 1.2, 1, 1.3, 1.1.1, 5.6, 1.1.10, 4, 1.1.9, 1.2.1.10, 2.1.1.4.5, 1.2.1.9, 1.2.1, 2.2.2, 1.2.1.11]
SORTED: [1, 1.1, 1.1.1, 1.1.9, 1.1.10, 1.2, 1.2.1, 1.2.1.9, 1.2.1.10, 1.2.1.11, 1.3, 2.1.1.4.5, 2.2.2, 4, 5.6]
I have recently had a need to do this in a more generic way for arbitrary file names, similar to how Windows Explorer sorts files:
I wrote a blog post about this. The idea was inspired by this answer here. The comparator used for ordering files this way looks like this:
public final class FilenameComparator implements Comparator<String> {
private static final Pattern NUMBERS =
Pattern.compile("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
#Override
public final int compare(String o1, String o2) {
// Optional "NULLS LAST" semantics:
if (o1 == null || o2 == null)
return o1 == null ? o2 == null ? 0 : -1 : 1;
// Splitting both input strings by the above patterns
String[] split1 = NUMBERS.split(o1);
String[] split2 = NUMBERS.split(o2);
for (int i = 0; i < Math.min(split1.length, split2.length); i++) {
char c1 = split1[i].charAt(0);
char c2 = split2[i].charAt(0);
int cmp = 0;
// If both segments start with a digit, sort them numerically using
// BigInteger to stay safe
if (c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9')
cmp = new BigInteger(split1[i]).compareTo(new BigInteger(split2[i]));
// If we haven't sorted numerically before, or if numeric sorting yielded
// equality (e.g 007 and 7) then sort lexicographically
if (cmp == 0)
cmp = split1[i].compareTo(split2[i]);
// Abort once some prefix has unequal ordering
if (cmp != 0)
return cmp;
}
// If we reach this, then both strings have equally ordered prefixes, but
// maybe one string is longer than the other (i.e. has more segments)
return split1.length - split2.length;
}
}
If you want to sort some versions (e.g. 0.4.3, 5.3.5, 1.2.4) you could use my approach which includes using a java.util.Comparator. To use this you have to use a sorting method (e.g. Arrays.sort(new String[] {"0.4.3", "5.3.5", "1.2.4"}, new VersionComparator())). The VersionComparator class is written below:
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public final class VersionComparator implements Comparator<String> {
#Override
public int compare(String version1, String version2) {
if (checkVersionFormat(version1) == false || checkVersionFormat(version2) == false) {
System.out.println("One of the given versions uses a false format");
}
List<String> firstVersionElements = Arrays.asList(version1.split("\\."));
List<String> secondVersionElements = Arrays.asList(version2.split("\\."));
int maxVersionElements = getMaxNumber(firstVersionElements.size(), secondVersionElements.size(), 0);
for (int counter = 0; counter < maxVersionElements; counter++) {
if (firstVersionElements.size() == counter && secondVersionElements.size() == counter) {
return 0;
}
if (firstVersionElements.size() == counter) {
return 1;
}
if (secondVersionElements.size() == counter) {
return -1;
}
int firstIntElement = Integer.valueOf(firstVersionElements.get(counter));
int secondIntElement = Integer.valueOf(secondVersionElements.get(counter));
if (firstIntElement < secondIntElement) {
return 1;
}
if (firstIntElement > secondIntElement) {
return -1;
}
}
return 0;
}
private boolean checkVersionFormat(String version) {
String versionCopy = new String(version);
String[] validChars = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "." };
for (String character : validChars) {
versionCopy = versionCopy.replace(character, "");
}
return versionCopy.equals("");
}
public static int getMaxNumber(Integer... ints) {
int maximumInt = ints[0];
for (int processInt : ints) {
if (processInt > maximumInt) {
maximumInt = processInt;
}
}
return maximumInt;
}
}
From your comments in your code above the specialCompare method…
Meant for when version numbers such as 2 and 2.0 arise. This method
will make sure to put the smaller version number (in length) first
So I am guessing from this that you want the version to be sorted by the length of the version number. Example: from your supplied versions string array you want to sort as below…
0
2
0.0
0.1
1.2
1.113
2.0
0.0.0
1.1.1
1.2.1
2.0.0
0.0.0.1
If this is the case, then you seem to be making this more complicated than it has to be. When you get two versions where the version lengths differ, then the one with the shorter version length should go first. So a simple check on the length of the version split arrays should solve this. If they are the same length, then you need to check each version. There is no need for a specialCompare method when the version lengths are the same. Simply check each version and if they are the same, then go to the next version number and so on. As soon as one version is different then you will know what to return. If you go through the whole array then you know all the version numbers are the same.
Below is a change to the compareVersion method using the logic above. There is no need for a specialCompare method. I am guessing this is what you are looking for.
public static int compareVersion(String version1, String version2)
{
String[] arr1 = version1.split("\\.");
String[] arr2 = version2.split("\\.");
if (arr1.length < arr2.length)
return -1;
if (arr1.length > arr2.length)
return 1;
// same number of version "." dots
for (int i = 0; i < arr1.length; i++)
{
if(Integer.parseInt(arr1[i]) < Integer.parseInt(arr2[i]))
return -1;
if(Integer.parseInt(arr1[i]) > Integer.parseInt(arr2[i]))
return 1;
}
// went through all version numbers and they are all the same
return 0;
}
package com.e;
import java.util.*;
/**
* Created by dpc on 17-2-27.
*
*/
public class VersionComparator implements Comparator {
#Override
public int compare(String o1, String o2) {
if (o1 == null && o2 == null) {
return 0;
} else if (o1 == null && o2 != null) {
return -1;
} else if (o1 != null && o2 == null) {
return 1;
} else {
if (o1.length() == 0 && o2.length() == 0) {
return 0;
} else if (o1.length() == 0 && o2.length() > 0) {
return -1;
} else if (o1.length() > 0 && o2.length() == 0) {
return 1;
} else {
return compareVersion(o1, o2);
}
}
}
public static int compareVersion(String version1, String version2) {
String[] arr1 = version1.split("\\.");
String[] arr2 = version2.split("\\.");
try {
int i = 0;
while (i < arr1.length || i < arr2.length) {
if (i < arr1.length && i < arr2.length) {
if (Integer.parseInt(arr1[i]) < Integer.parseInt(arr2[i])) {
return -1;
} else if (Integer.parseInt(arr1[i]) > Integer.parseInt(arr2[i])) {
return 1;
} else if (Integer.parseInt(arr1[i]) == Integer.parseInt(arr2[i])) {
int result = specialCompare(version1, version2);
if (result != 0) {
return result;
}
}
} else if (i < arr1.length) {
if (Integer.parseInt(arr1[i]) != 0) {
return 1;
}
} else if (i < arr2.length) {
if (Integer.parseInt(arr2[i]) != 0) {
return -1;
}
}
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static int specialCompare(String str1, String str2) {
String[] arr1 = str1.split("\\.");
String[] arr2 = str2.split("\\.");
for (int i = 1; i < arr1.length; i++) {
if (Integer.parseInt(arr1[i]) != 0) {
return 0;
}
}
for (int j = 1; j < arr2.length; j++) {
if (Integer.parseInt(arr2[j]) != 0) {
return 0;
}
}
if (arr1.length < arr2.length) {
return -1;
} else {
return 1;
}
}
// test
public static List<String> getLowerList(String str, Comparator<String> comparator, List<String> list) {
if (str == null) {
return list;
}
List<String> newlist = new ArrayList<String>();
newlist.add(str);
newlist.addAll(list);
// sort
Collections.sort(newlist, comparator);
// search
int endIndex = Collections.binarySearch(newlist, str);
if (endIndex >= 0) {
// sublist 0 1
return newlist.subList(0, endIndex + 1);
} else {
return new ArrayList<String>();
}
}
public static void main(String[] args) {
List<String> test1 = Arrays.asList(new String[]{
"2.1.1", "1.21.22", "1.21.25", "1.113", "0.0.0.1",
"2.0.0", "1.2", "2.0", "0.1", "1.2.1", "1.1.1",
"11", "100", "" + Integer.MAX_VALUE + ".1", "",
"2.0", "10.1"});
List<String> test2 = Arrays.asList(new String[]{"", null, "0", "10.20.100", "3.1.1", "9.8", "10.3.92"});
List<String> newlist = new ArrayList<String>();
newlist.addAll(test1);
newlist.addAll(test2);
Collections.sort(newlist, new VersionComparator());
VersionComparator compareVersion = new VersionComparator();
System.out.println(newlist);
System.out.println(getLowerList("2", compareVersion, newlist));
System.out.println(getLowerList("3", compareVersion, newlist));
System.out.println(getLowerList("4", compareVersion, newlist));
System.out.println(getLowerList("5", compareVersion, newlist));
}
}
I was given this project by a friend who is coding in school, but I am trying to find a better way to code it. It is calling different Boolean methods, checking if true and adding to a count for latter use.
public static void testHand(PokerHand d) {
if (d.isRoyalFlush()) {
royalFlush++;
} else if (d.isStraightFlush()) {
straightFlush++;
} else if (d.is4OfAKind()) {
fourtOfAKind++;
} else if (d.isFullHouse()) {
fullHouse++;
} else if (d.isFlush()) {
flush++;
} else if (d.isStraight()) {
straight++;
} else if (d.is3OfAKind()) {
threeOfAKind++;
} else if (d.is2Pair()) {
twoPair++;
} else if (d.isPair()) {
pair++;
} else if(d.isHighCard()){
highCard++;
}
}
The code for PokerHand is as follows:
public class PokerHand {
private Card[] hand; // the hand of 5 cards
// the default constructor
public PokerHand() {
hand = new Card[5];
}
// A constructor to help with testing
public PokerHand(Card c0, Card c1, Card c2, Card c3, Card c4) {
hand = new Card[5];
hand[0] = c0;
hand[1] = c1;
hand[2] = c2;
hand[3] = c3;
hand[4] = c4;
}
/* This methods fills the hand with cards from the deck.
It uses an insertion sort so that the cards are ordered by rank.*/
public void fillHand(Deck deck) {
for (int i = 0; i < 5; i++) {
int j = i - 1;
Card temp = deck.dealCard();
while (j >= 0 && hand[j].getRank() > temp.getRank()) {
hand[j + 1] = hand[j];
j--;
}
hand[j + 1] = temp;
}
}
//PLACE ADDITIONAL METHODS AFTER THIS COMMENT
/*Checking for Royal flush by first checking if straight flush
and then if highest card is an Ace.*/
public boolean isRoyalFlush() {
return (isStraightFlush() && hand[4].getRank() == 14);
}
//Check for Straight Flush by seeing if it is both a straight and a flush
public boolean isStraightFlush() {
return (isFlush() && isStraight());
}
/*Checking if hand is a Four-of-a-kind. Done by looking at first card and
checking if it equals next 3 cards. If not, then checking second card and
checking if it equals next three cards.*/
public boolean is4OfAKind() {
boolean isFour = false;
for (int i = 0; i < hand.length - 3; i++) {
int card = hand[i].getRank();
if (card == hand[i + 1].getRank()
&& card == hand[i + 2].getRank()
&& card == hand[i + 3].getRank()) {
isFour = true;
}
}
return isFour;
}
//Checking if hand holds a Full House By:
public boolean isFullHouse() {
//Setting two boolean values
boolean a1, a2;
//First checking if it is a pair followed by a 3-of-a-kind.
a1 = hand[0].getRank() == hand[1].getRank() &&
hand[2].getRank() ==hand[3].getRank() && hand[3].getRank() == hand[4].getRank();
//Second, checking if it is 3-of-a-cind followed by a pair
a2 = hand[0].getRank() == hand[1].getRank() && hand[1].getRank() == hand[2].getRank() &&
hand[3].getRank() == hand[4].getRank();
//Returns true if it is either.
return (a1 || a2);
}
/*Checking if hand is a Flush by first getting the first card's suit
and checking if it is the same for all cards.*/
public boolean isFlush() {
String suit = hand[0].getSuit();
return hand[1].getSuit().equals(suit)
&& hand[2].getSuit().equals(suit)
&& hand[3].getSuit().equals(suit)
&& hand[4].getSuit().equals(suit);
}
/*Checking id hand is a Straight by first getting the rank of the first
card, then checking if the following cards are incremented by 1*/
public boolean isStraight() {
int card = hand[0].getRank();
return (hand[1].getRank() == (card + 1) &&
hand[2].getRank() == (card + 2) &&
hand[3].getRank() == (card + 3) &&
hand[4].getRank() == (card + 4));
}
/*Checking if hand is a Three-of-a-kind. Done by looking at first card and
checking if it equals next 2 cards. If not, then checking next card and
checking if it equals next 2 cards. This is done three times in total.*/
public boolean is3OfAKind() {
boolean threeKind = false;
for (int i = 0; i < hand.length - 2; i++) {
int card = hand[i].getRank();
if (card == hand[i + 1].getRank() &&
card == hand[i + 2].getRank()) {
threeKind = true;
}
}
return threeKind;
}
//Checking hand for 2 pairs by:
public boolean is2Pair() {
int count = 0; // Number of pairs.
int firstPair = 0; //If pair found, store rank.
//Go through hand
for (int i = 0; i < hand.length - 1; i++) {
int card = hand[i].getRank();
//Finding pairs. Cannot be same rank pairs.
if (card == hand[i + 1].getRank() && card != firstPair) {
firstPair = card;
count++;
}
}
return count == 2;
}
/*Checking if hand is a Pair. Done by looking at first card and
checking if it equals the next card. If not, then it checks the next card and
sees if it equals the next card. This is done four times in total.*/
public boolean isPair() {
boolean isPair = false;
for (int i = 0; i < hand.length - 1; i++) {
int card = hand[i].getRank();
if (card == hand[i + 1].getRank()) {
isPair = true;
}
}
return isPair;
}
//If hand is not equal to anything above, it must be High Card.
public boolean isHighCard() {
return !(isRoyalFlush() || isStraightFlush() || is4OfAKind()
|| isFullHouse() || isFlush() || isStraight()
|| is3OfAKind() || is2Pair() || isPair());
}
}
You could use the ternary operator ? : to shorten the code. Like
public static void testHand(PokerHand d) {
royalFlush += d.isRoyalFlush() ? 1 : 0;
straightFlush += d.isStraightFlush() ? 1 : 0;
fourtOfAKind += d.is4OfAKind() ? 1 : 0; // <-- this appears to be a typo.
fullHouse += d.isFullHouse() ? 1 : 0;
flush += d.isFlush() ? 1 : 0;
straight += d.isStraight() ? 1 : 0;
threeOfAKind += d.is3OfAKind() ? 1 : 0;
twoPair += d.is2Pair() ? 1 : 0;
pair += d.isPair() ? 1 : 0;
highCard += d.isHighCard() ? 1 : 0;
}
Alternatively, you could encode the hand types with an enum. Give the PokerHand a HandType (or create a factory method). Something like,
enum HandType {
ROYALFLUSH, STRAIGHTFLUSH, FOUROFAKIND, FULLHOUSE, FLUSH,
STRAIGHT, THREEOFAKIND, TWOPAIR, PAIR, HIGHCARD;
static HandType fromHand(PokerHand d) {
if (d.isRoyalFlush()) {
return ROYALFLUSH;
} else if (d.isStraightFlush()) {
return STRAIGHTFLUSH;
} else if (d.is4OfAKind()) {
return FOUROFAKIND;
} else if (d.isFullHouse()) {
return FULLHOUSE;
} else if (d.isFlush()) {
return FLUSH;
} else if (d.isStraight()) {
return STRAIGHT;
} else if (d.is3OfAKind()) {
return THREEOFAKIND;
} else if (d.is2Pair()) {
return TWOPAIR;
} else if (d.isPair()) {
return PAIR;
} else {
return HIGHCARD;
}
}
}
Then you can create an array of counts for testHand like
private static int[] handCounts = new int[HandType.values().length];
public static void testHand(PokerHand d) {
handCounts[HandType.fromHand(d)]++;
}
I would suggest you model the potential hands as an enum. They are a good use case because they have a fixed set of members.
Something like the following:
enum Rank {
ROYAL_FLUSH(Hand::isRoyalFlush),
FOUR_OF_A_KIND(Hand::isFourOfAKind),
...
public static Rank getRank(Hand hand) {
for (Rank rank: values()) {
if (rank.test.test(hand))
return rank;
}
throw new IllegalStateException("No rank for hand " + hand.toString());
}
private final Predicate<Hand> test;
Rank(Predicate<Hand> test) {
this.test = test;
}
}
Then all your if statements can be replaced by Rank.getRank(hand).
Maybe the switch statement will suit your needs :
switch (d) {
case d.isRoyalFlush() : royalFlush++; break;
case d.isStraightFlush(): straightFlush++; break;
... ... ...
default : do-something();
}
This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 7 years ago.
This is my where i create my card
package javaapplication21;
public class Card {
private String Name = null;
private String Description = null;
private String Type = null;
public Card(int i, int j) {
if (i == 0) {
Type = "Spades";
} else if (i == 1) {
Type = "Diamonds";
} else if (i == 2) {
Type = "Hearts";
} else if (i == 3) {
Type = "Clubs";
}
int Value = j;
if (j == 11) {
Name = "Jack";
} else if (j == 12) {
Name = "Queen";
} else if (j == 13) {
Name = "King";
} else if (j == 1) {
Name = "Ace";
} else if (j == 14) {
Name = "Joker";
} else {
Name = "" + Value;
}
}
public String getDescription() {
Description="Its a"+Name+"of"+Type;
return this.Description;
}
}
package javaapplication21;
import java.util.ArrayList;
public class JavaApplication21 {
public static void main(String[] args) {
ArrayList Deck=new ArrayList<Card>();
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 15; j++) {
new Card(i, j);
Deck.add(new Card(i, j));
}
}
System.out.println(Deck.get(5).getDescription());
}
}
I get an error(Cannot find Symbol) when trying to use the getDescription of the card object in index 5 of the deck. I m new to programming but i really don't know what's the problem.
The arraylist does not know about type of the stored objects. You got to define the type.
ArrayList<Card> deck = new ArrayList<Card>();
get() method of ArrayList return object of type Object class and Object class doesnt have getDescription()
You should cast it to Card class -(Card)Deck.get(5)