I am making a poker game and to generate a hand that contains non-duplicated I decided to use a HashSet and for-loop to give the player 5 cards.
public class CardDriver {
public static void main(String[] args) {
Set<Card> hands = new HashSet<Card>();
while(hands.size()!= 5) {
hands.add(new Card());
}
System.out.println("Player 1: " + hands);
}
}
The Card constructor:
public Card() {
Random nb = new Random();
int switchNb = nb.nextInt(13) + 1;
switch(switchNb)
{
case 1: value = Value.Ace; break;
case 2: value = Value.Two; break;
....
case 11: value = Value.Jack; break;
case 12: value = Value.Queen; break;
case 13: value = Value.King; break;
}
switchNb = nb.nextInt(4) + 1;
switch(switchNb)
{
case 1: suite = Suite.Hearts; break;
case 2: suite = Suite.Diamonds; break;
case 3: suite = Suite.Clubs; break;
case 4: suite = Suite.Spades; break;
}
}
I am faced with three problems and I believe that both can be solved once I figure out how to isolate certain elements (if it is even possible) from the player's hand.
First off I need to use the same HashSet to give 5 more cards to the second player and so on. For example I would have elements 1-5 of the Set go to player 1 and 6-10 go to player 2.
Also, by being able to isolate a card from the set, it would also enable me to replace a card (video poker).
Lastly, I figured that by being able to isolate each card in the user's hand, it would make it easier for me to analyze the value of the hand each player has. I am not very experience when it comes to using sets so perhaps it would be better to use an array?
Edit: Example of an output:
Player 1: [Three of Hearts, King of Clubs, Ten of Clubs, Two of Spades, Ace of Hearts]
Related
I have different fields using the same parameters i.e. same grading scale. I want to use switch statement to return grades for different fields using the same scale. Something like this. I thought that there was something like this: switch (attend, job, initiative) { that would combine the three variables.
int attend = 5;
int job = 5;
int initiative = 5;
switch (attend) {
case 1:
getattendo = 5;
break;
case 2:
getattendo = 4;
break;
case 3:
getattendo = 3;
break;
case 4:
getattendo = 2;
case 5:
getattendo = 1;
break;
default:
getattendo = 0; // null
}
Your help is appreciated.
fmk
Enum works well with switch cases. So, you can define an enum that represents your range of value of it is a finite and reasonable range of values :
public enum OPTIONS {
OPTION1(5, 5, 5),
OPTION2(5, 2, 4),
OPTION3(1, 2, 3),
OPTION4(4, 4, 1);
private final int attend;
private final int jobs;
private final int initiative;
Directive(int attend, int jobs, int initiative) {
this.attend = attend;
this.jobs = jobs;
this.initiative = initiative;
}
// ... optional setters & getters
}
Given your create OPTION Enum, you can use a switch to handle the different cases :
switch (OPTION) {
case OPTION1:
getattendo = 5;
break;
case OPTION2:
getattendo = 4;
break;
case OPTION3:
getattendo = 3;
break;
case OPTION4:
getattendo = 2;
break;
default:
getattendo = 0; // null
break;
}
Note: Your switch is legitimate only if you have a finite number of condition. Otherwise, use a method to calculate your result.
A trick you use utilizes the unary or operation for checking binary digit presence.
This will help get you started on switching according to various conditions.
This is similar to how file permissions work in Linux.
public class ScoreCombinator {
public static final int ATTEND = 1; // binary: 001
public static final int JOB = 2; // binary: 010
public static final int INITIATIVE = 4; // binary: 100
public static void main(String[] args) {
evaluate(ATTEND | INITIATIVE); // Attend and Initiative
evaluate(INITIATIVE | ATTEND | JOB); // Attend, Job, and Initiative
}
private static void evaluate(int value) {
switch (value) {
case ATTEND: {
System.out.println("Attend");
break;
}
case ATTEND | JOB: {
System.out.println("Attend and Job");
break;
}
case ATTEND | JOB | INITIATIVE: {
System.out.println("Attend, Job, and Initiative");
break;
}
case ATTEND | INITIATIVE: {
System.out.println("Attend and Initiative");
break;
}
case JOB: {
System.out.println("Job");
break;
}
case JOB | INITIATIVE: {
System.out.println("Job and Initiative");
break;
}
case INITIATIVE: {
System.out.println("Initiative");
break;
}
}
}
}
Something like switch(a,b,c) is not possible.
If all values are the same, just use one of the valueslandmaybe verify that all values are the same).
However, there are workarounds if you want to switch-case with multiple numbers:
mathematical solution
For example, you could use prime numbers for this. As you only want to switch numbers, this is possible as long as there is a prime number higher than the highest expected value(for attend, prime and job).
Instead of switch(attend, job, initiative), you use switch((attend*prime+job)*prime+initiative) and instead of case (exampleAttend, exampleJob, exampleInitiative):, you use case ((exampleAttend*prime+exampleJob)*prime+exampleInitiative):
Note that prime must be the same in the switch and case statements.
Note that you should test if any of the input numbers is higher than the prime. This would logically lead to the default case but it could lead to collissions.
You may also want to make sure that the prime to the forth power is lower than the max value of the data type or there may be overflows.
On the other side, this method should be more performant than the second.
simple string concadation
Another option is to work with strings. As the string representation of a number is unique (to the number) and it does not contain some characters (like spaces), you can concadate those numbers and use such a character to seperate them.
Instead of switch(attend, job, initiative), you use switch(attend+" "+job+" "+initiative) and instead of case (exampleAttend,exampleJob,exampleInitiative):, you use case (exampleAttend+" "+exampleJob+" "+exampleInitiative):.
This is obviously easier and fail-safer than the first method involving prime numbers but there should be a performance impact as concadating strings is slower than multiplying ints.
Another possibility is to use enums. Look at the other answer by #Hassam Abdelillah
if you want to know how this works. If you like the enum approach, feel free to upvote the other answer.
Is there a way to grab the resulting number from each iteration of this loop and compare it to the next?
This is a Slot Machine Sim in Java,
I'm trying to find a way to see how many of the results match.
so I thought I would capture the number that is resulted from each round of the For loop and compare it to the previous one.
but I have no idea how to write that?
is there a better way to do this?
what I have so far:
for (int count=1; count<= 3 ; ++count)
{
number = slotM.nextInt(6);
switch (number)
{
case 0:
System.out.print("-cherries-");
break;
case 1:
System.out.print("-Oranges-");
break;
case 2:
System.out.print("-Palms-");
break;
case 3:
System.out.print("-Bells-");
break;
case 4:
System.out.print("-Melones-");
break;
default:
System.out.print("-Bars-");
break;
}
System.out.print(number);
}
Yep there are several better ways. If you have a fixed number of options (6 in your case) an enum might be a good option:
enum Picture {
CHERRIES, ORANGES, PALMS, BELLS, MELONS, BARS;
public String getName() {
return "-" + name().substring(0, 1) + name().substring(1).toLowerCase() + "-";
}
That way you can store your numbers as pictures rather than numbers.
Picture pictures[3];
Random random = new Random();
for (int i = 0; i < pictures.length; i++)
picture[i] = Picture.values[random.nextInt(pictures.length)];
To get the printed version:
for (Picture picture: picture)
System.out.print(picture.getName());
You’ll need some kind of storage outside of the loop so that each iteration can reference it.
int[] results Look in to arrays - you can put the results of each round into a part of the array, and look up the value.
You are declaring your count variable in the for loop, just declare outside and make a comparison with it
I am currently using IntelliJ and an error that says "Duplicate label '2'" appears when I am placing a case for pressing the CANCEL option in my menu.
import javax.swing.*;
public class Main {
public static void main(String[] args){
int choice=0;
Object menu= "1. Name Constructor\n" +
"2. Pretty Printing of text\n" +
"3. FLAMES\n" +
"4. Your Superhero name!\n" +
"5. return to the main menu\n";
do {
choice = Integer.parseInt(JOptionPane.showInputDialog(null,
"S T R I N G M A N I P U L A T I O N M E N U\n" +
menu, "Menu", 1));
switch (choice) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case JOptionPane.CANCEL_OPTION:
break;
default:
JOptionPane.showMessageDialog(null,"Enter a valid choice.","Error",1);
break;
}
}while(choice!=5);
}
}
That is happening because you can't define two cases with the same value in the switch statement.
If you take a look inside the JOptionPane, you'll see that the CANCEL_OPTION value is 2.
Here is the part of the JOptionPane class that shows the value:
/** Return value from class method if CANCEL is chosen. */
public static final int CANCEL_OPTION = 2;
As you already have a case 2: and the CANCEL_OPTION also returns 2, you have to change it. For example, if you change to case 6: it will work. Give it a try.
here you can see all the values that a JOptionPane has, so you can modify your case according to other values, so you don't get this duplicate case error anymore.
I have a TableView with 4 parts of the field. which in every field filled images A, B, C and D. You can see in the image below :
My question is how do I make the image appear randomly when the activity start ? Like this one :
Thanks for the questions !
You can always use the static random-method in the Math-class and then create a switch structure
int square = ((int)(Math.random() * 4) + 1);
switch (square) {
case 1:
// .. code
break;
case 2:
// .. code
break;
case 3:
// .. code
break;
case 4:
// .. code
break;
}
You can use
int min = 1;
int max = 4;
Random r = new Random();
int i = r.nextInt(max - min + 1) + min;
switch(i) {
case 0:
// .. code
break;
case 1:
// .. code
break;
case 2:
// .. code
break;
case 3:
// .. code
break;
}
There are many logics... Pseudocode of the one, I can think of right now is as follow:
Step 1: Save image resource info (path) in HashMap with key as 0 to 3.
Step 2: Generate Math.random() between 0 and 3
Step 3: Fetch the image from HashMap with the number got in step 2.
Step 4: Show it in the table.
Hope this helps. All the best.
I'm sure there are better examples than mine:)
Let's say that it's snowing and the users can earn points for each snowflake, but they have to do it fast to no get stuck in the snow, so this is my ex:
class apples{
public static void main(String args[]){
int points;
points = 1;
switch (points){
case 1:
System.out.println("32");
break;
case 2:
System.out.println("Almost half");
break;
case 3:
System.out.println("You're near");
break;
case 4:
System.out.println("Congratulations., You got 100 points");
default:
System.out.println("Want to start again?");
break;
}
}
}
The switch statement has been miss-used for a long time.
The original idea was to have an entry point system; a goto-like statement which worked like this :
If my value is 1; goto 1;
Else If my value is 2; goto 2;
Else If my value is 3; goto 3;
Else If goto default;
label 1 : ...;
label 2 : ...;
label 3 : ...;
label default : ...;
And people started to like this system and decided that it would be better than having a lot of if/else statements. So they used a little trick, the break; And now people really enjoy the switch as a replacement of the if/else by breaking every case of the switch.
To have a really good example of the original switch statement, you should have something like this:
public void printDaysLeftUntilNextMonday(){
switch(dayOfWeek){
case 1 :
System.out.println("Monday");
case 2 :
System.out.println("Tuesday");
case 3 :
System.out.println("Wednesday");
case 4 :
System.out.println("Thursday");
case 5 :
System.out.println("Friday");
case 6 :
System.out.println("Saturday");
case 7 :
System.out.println("Sunday");
}
}
I had a real use case on day (rare thing if you don't abuse of break; in switch) it was in a Hangman.
public void printHangman(){
switch(triesLeft){
case 1 :
printLeftLeg();
case 2 :
printRightLeg();
case 3 :
printLeftArm();
case 4 :
printRightArm();
case 5 :
printBody();
case 6 :
printHead();
}
}
If you want to have more flexibility than a HashMap (not that there's anything wrong with the solution), you can go with a chain of responsibility :
class PointScore {
private PointScore next;
private int points;
private String msg;
public PointScore(int points, String msg) {
this.points = points;
this.msg = msg;
this.next = null;
}
public PointScore setNext(PointScore next) {
this.next = next;
return next;
}
public boolean checkScore(int points) {
if (this.points == points) {
System.out.println(this.msg);
return true;
} else if (null != next) {
return next.checkScore(points);
} else {
return false;
}
}
}
Then your main entry point :
class Apples {
public static void main(String...args) {
int points;
points = 1;
// set first condition (highest priority first)
PointScore scores = new PointScore(4, "Congratulations., You got 100 points");
// set next chain members in order or priority (highest to lowest)
scores.setNext(new PointScore(3, "You're near"))
.setNext(new PointScore(2, "Almost half"))
.setNext(new PointScore(1, "32"));
if (!scores.checkScore(points)) {
System.out.println("Want to start again?");
}
}
}
This doesn't look much, but the checkScore method can perform other checks; for example, you could setup a range of values instead of a single points integer, etc.
Use a dictionary or a hashmap to map the number of points to the string.
I find switch statements make most sense when the range of a variable is bounded. So for example the days-of-the-week example given here is fine, and the one with the enum is even better.
Bit of a no-brainer, but wikipedia has an excellent page with the history, advantages and disadvantages of the switch statement, as well as a host of examples in different languages.
Okay here we go. At work we often use enum types, simple example:
public enum Colors {
RED,
GREEN,
BLUE,
YELLOW,
VIOLET,
BROWN,
ORANGE; // more to come
}
so we can switch over these literal constants:
public String colorToMood(final Colors color) {
String mood = "everything the same to me";
switch (color) {
case RED:
mood = "excited";
break;
case YELLOW:
mood = "I like the sun";
break;
case GREEN:
mood = "forests are nice";
break;
case BLUE:
mood = "I feel free like a bird in the sky";
break;
// fill in your code here for VIOLET, BROWN, ORANGE
// otherwise they get handled by the default clause
default:
mood = "I don't know your color";
break;
}
return mood;
}
Maybe you now get a better idea what the benefits of a switch in conjunction with enums are. You can even define a constructor for your enum constants, but that gets too advanced...