简体   繁体   中英

Need Guidance on Parsing an Input in Java, Need to Specifically Use Classes, having a Hard time understanding Constructors

The Assignment i'm trying to complete is below; I don't need the whole answer but any kind of help or guidance would be nice as my professor is dodging my questions. Thank you so much! Doing everything I can to grasp these concepts. Here is the Assignment: Create a program called PlayCards. This class will use another class called Card. Put both classes in the same file, but create the program as "PlayCards".

Create a class that represents a playing card (call it Card) and another class (call it PlayCards) that uses this class.

Card will have two fields: rank and suit. Use ints for both rank and suit. For rank, use values 2 through 10 to represent ranks 2 through 10, and 11 for Jack, 12 for Queen, 13 for King, and 14 for Ace. For suit, use 0 for Clubs, 1 for Diamonds, 2 for Hearts, and 3 for Spades.

Only the PlayCards class will have a main() method. This method should read args of the form "7-S KH 2-H 4-C JD". Each arg stands for a card. The first part is the rank and the second part is the suit. C is for Clubs, D is for Diamonds, H is for Hearts, and S is for Spades.

For each arg, your program must parse the arg, create a Card object representing the card. Example:

4 ♥ King ♣ 2 ♠ Queen ♦ 10 ♣

To print the suit symbols, use "♥", "♣", "♠", and "&diamonds;"

And Here is my Code so far:

class PlayCards
{
    public static void main(String[] args)
    {
        Card c1 = new Card(17, 3);
    }
}
class Card
{
    private int Rank;
    private int Suit;

    public Card() {
        //Declaring of Object
    }

     public Card(int Rank, int Suit) {
        if (14 < Rank || Rank < 2) {
            System.out.println("Error: This Card does not exist.")
        }
        System.out.println("Hi from the Card Constructor. The Key to successful completion of this assignment.");
        this.Rank = Rank;
        this.Suit = Suit;
    }
}

** I know it is small but that's only because I scrapped what I had the other file to start somewhat fresh. I had a way of doing it detecting the prescence of the characters with If statements, but i'm having a hard time because it needs to be completed with Objects and an additional Class. As always Thank you to anyone who takes the time help, it is always beyond appreciated! - Synergy

For any java program, main method is the first thread that's get executed. You can think of it as an entrypoint for your code. Now, in your case the main method is present in the PlayCards class and so it gets executed first. Now this method can interact with the external world via arguments specified to it. Those arguments are passed to the code via a String array called args. You can see it present as an argument to the main method.

Now you can access each argument individually as args[0], args[1] and so on. Since each of these elements is a string you can perform inbuilt string operations on top of them. split() is one such method. String tokenizer is one such class that does the same. You can read more about them on java docs.

Once you split the arguments like "7-H" to "7" and "H", you can parse the Integer to string directly using something like parseInt() method. Again, you should read up on the documentation online. Now that you have converted "7" to 7, you can use either substitution or some other way to replace "H" by its number equivalent.

From here it should be easy for you.

Assignment Task

  • In the assignment, It is given that you have to make two classes PlayingCards consisting of the main function, hence it will be the runner class and Card which will have two integer members rank and suit .
  • The input will be a string in the form 7-H 4-S AS KD , where each the card is separated by a space.
  • The task is to convert each card into a Card object

Approach

  • Firstly, convert the input-string to the array of different card-strings by splitting the string by white-space .
  • After splitting, The array should look like ["7-H", "4-S", "AS", "KD"] .
  • Now, loop through the array and split each card-string again by hyphen which will give rank-string and suit-string
  • Now, Switch rank-string & suit-string to get rank and suit
  • Finally, Create Card object using the rank and suit

Solution

imports

import java.util.ArrayList;

class Card

class Card {
    private final int rank;
    private final int suit;

    Card(int rank, int suit) {
        this.rank = rank;
        this.suit = suit;
    }

    public String getCardDetails() {
        String rankString;
        if (rank > 1 && rank <= 10) {
            rankString = String.valueOf(rank);
        } else {
            rankString = switch (rank) {
                case 11 -> "Jack";
                case 12 -> "Queen";
                case 13 -> "King";
                case 14 -> "Ace";
                default -> "🚫";
            };
        }
        String suitSymbol = switch (suit) {
            case 0 -> "♣";
            case 1 -> "♦";
            case 2 -> "♥";
            case 3 -> "♠";
            default -> "🚫";
        };
        return String.format("%s %s", rankString, suitSymbol);
    }
}

class PlayingCards

public class PlayCards {
    public static void main(String[] args) {
        String input = "7-S K-H 2-H 4-C J-D";
        String[] inputs = input.split(" ");

        ArrayList<Card> cards = new ArrayList<>();

        for (String in : inputs) {
            String[] temp = in.split("-");

            int rank = switch (temp[0].charAt(0)) {
                case 'J' -> 11;
                case 'Q' -> 12;
                case 'K' -> 13;
                case 'A' -> 14;
                default -> Integer.parseInt(temp[0]);
            };
            int suit = switch (temp[1]) {
                case "S" -> 0;
                case "D" -> 1;
                case "H" -> 2;
                case "C" -> 3;
                default -> -1;
            };
            Card card = new Card(rank, suit);
            cards.add(card);
        }

        for (Card card : cards) {
            System.out.println(card.getCardDetails());
        }
    }
}

output

7♣
King♥
2♥
4♠
Jack♦

split string without split() function

String input = "7-S K-H 2-H 4-C J-D";
ArrayList<String> subStrings = new ArrayList<>();
int begin = 0, forward;
for (int i = 0; i < input.length(); i++) {
    if (input.charAt(i) == ' ') {
    forward = I;

    StringBuilder str = new StringBuilder();
    for (int j = begin; j < forward; j++) {
        str.append(input.charAt(j));
    }
    begin = i + 1;
    subStrings.add(String.valueOf(str));
    }
}
StringBuilder str = new StringBuilder();
for (int k = begin; k < input.length(); k++) {
    str.append(input.charAt(k));
}
subStrings.add(String.valueOf(str));

output

[7-S, K-H, 2-H, 4-C, J-D]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM