How can I Use numbers and letters in a String -- Java

317 views Asked by At

I am currently working on a java project in which I must use the cards of a normal deck.

I would like to make a String Cards to hold the value of the different cards. I started with this.

String Card = "12345678910JQK"

I realized it was not the right way because the 10 is actually a 1 and then a 0 I am wondering if it is possible to make a String with number and letters.

5

There are 5 answers

1
marianopicco On

In this case, since it's a finite number of things you want to represent, why not use an Enum with all the values for the cards?

Here you have some examples on enumaration, and it's explained with cards, it might be a good read:

https://howtoprogramwithjava.com/enums/

0
Andreas Hartmann On

You could use:

  • An enum
  • a String array
  • a Collection
  • A String but with a separator, e.g. 1,2,3,4...,9,10,J,... and use .split(',') to work with it.
1
Karan On

I doubt by using String you can solve this issue. If i was at your place i would have used Object array to solve this problem like

Object  obj[] = {1,2,3,4,5,6,"J","Q","K"};
 System.out.println(obj[8]);
 System.out.println(obj[1]);

lets wait for some answer to come on this .

0
Yohan Malshika On

you should use for this split(,) but before you should declare you string like this, String card="1,2,3,4,5,6,7,8,9,10,J,Q,K"

or you should use enum or String array for this problem.

1
Osusara Kammalawatta On

String array is the easiest way I think.

String[] cards = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};

then you can access each card as card[0], cards[1].