I am a beginner trying to create a program that selects two random cards from a deck. A pocket pair In doing this I am trying to test the if else if statements in the program. I have used if else if statements to handle the cases where the cards are the same, where the cards are the same twice, where the cards are the same three times and the case where they aren't the same. The if else if statements are either not working correctly or they are working correctly (probably) but I am using them improperly. I set generator.nextInt(2) so that I would have a greater chance at getting the same number to test the if else if statements.
Here is the code:
package ppselector; import java.io.IOException; import java.util.ArrayList; import java.util.Random; public class PPSelector { public static void main(String[] args) throws IOException { String card1 = " "; String card2 = " "; String pp = " "; int cardIndex1 = 0; int cardIndex2 = 0; ArrayList<String> myPP = new ArrayList<String>(); myPP.add("2c"); myPP.add("3c"); myPP.add("4c"); myPP.add("5c"); myPP.add("6c"); myPP.add("7c"); myPP.add("8c"); myPP.add("9c"); myPP.add("Tc"); myPP.add("Jc"); myPP.add("Qc"); myPP.add("Kc"); myPP.add("Ac"); cardIndex1 = 1; card1 = myPP.get(cardIndex1); cardIndex2 = 1; // if else if statements handle the case where card1 == card2 // chances of selecting the same two random numbers between // 1 and 52 three times in a row is slim if(cardIndex1 != cardIndex2){ card2 = myPP.get(cardIndex2); System.out.println("first"); }else if(cardIndex1 == cardIndex2){ cardIndex2 = generator.nextInt(2); card2 = myPP.get(cardIndex2); System.out.println("2nd"); System.out.println("card1:" + card1 + " cardIndex1:" + cardIndex1); System.out.println("card2:" + card2 + " cardIndex2:" + cardIndex2); }else if(cardIndex1 == cardIndex2){ cardIndex2 = generator.nextInt(2); card2 = myPP.get(cardIndex2); System.out.println("3rd"); }else { cardIndex2 = generator.nextInt(2); card2 = myPP.get(cardIndex2); System.out.println("last"); //System.out.print(cardIndex2 + ":" + card2 + " "); } System.out.print(card1 +" "+ card2); System.out.println(); } }
Here are the ouputs:
//when cardIndex1 = 0; //and cardIndex2 = 1; //Output: First 2c 3c //when cardIndex1 = 1; //and cardIndex2 = 1; //Output: 2nd card1:3c cardIndex1:1 card2:2c cardIndex2:0 3c 2c //Even though cardIndex1 = cardIndex2 going into the //if-else-if statements, they are not equal within the statements. Why is this? //when cardIndex1 = 1; //and cardIndex2 = 1; //Output: 2nd card1:3c cardIndex1:1 card2:3c cardIndex2:1 3c 3c //When cardIndex1 = cardIndex2 within the if else statement // it does not enter the next else if brackets. I want "3rd" or "last" to print. Why doesn't it?