简体   繁体   English

需要在 Java 中解析输入的指导,需要专门使用类,很难理解构造函数

[英]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.下面是作业: 创建一个名为 PlayCards 的程序。 This class will use another class called Card.这个类将使用另一个名为 Card 的类。 Put both classes in the same file, but create the program as "PlayCards".将两个类放在同一个文件中,但将程序创建为“PlayCards”。

Create a class that represents a playing card (call it Card) and another class (call it PlayCards) that uses this class.创建一个表示扑克牌的类(称为 Card)和另一个使用此类的类(称为 PlayCards)。

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.对于等级,使用值 2 到 10 表示等级 2 到 10,11 代表杰克,12 代表皇后,13 代表国王,14 代表王牌。 For suit, use 0 for Clubs, 1 for Diamonds, 2 for Hearts, and 3 for Spades.对于花色,梅花使用 0,方块使用 1,红心使用 2,黑桃使用 3。

Only the PlayCards class will have a main() method.只有 PlayCards 类有 main() 方法。 This method should read args of the form "7-S KH 2-H 4-C JD".此方法应读取“7-S KH 2-H 4-C JD”形式的参数。 Each arg stands for a card.每个 arg 代表一张卡片。 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. C代表梅花,D代表方块,H代表红心,S代表黑桃。

For each arg, your program must parse the arg, create a Card object representing the card.对于每个 arg,您的程序必须解析 arg,创建一个表示卡片的 Card 对象。 Example:例子:

4 ♥ King ♣ 2 ♠ Queen ♦ 10 ♣ 4♥国王♣2♠皇后♦10♣

To print the suit symbols, use "♥", "♣", "♠", and "&diamonds;"要打印西装符号,请使用“♥”、“♣”、“♠”和“&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.我有一种方法可以用 If 语句检测字符的存在,但我很难过,因为它需要用 Objects 和一个额外的 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.对于任何 java 程序,main 方法是第一个被执行的线程。 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.现在,在您的情况下,主要方法存在于 PlayCards 类中,因此它首先被执行。 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.这些参数通过名为 args 的字符串数组传递给代码。 You can see it present as an argument to the main method.您可以看到它作为 main 方法的参数出现。

Now you can access each argument individually as args[0], args[1] and so on.现在您可以单独访问每个参数,如 args[0]、args[1] 等。 Since each of these elements is a string you can perform inbuilt string operations on top of them.由于这些元素中的每一个都是一个字符串,因此您可以在它们之上执行内置的字符串操作。 split() is one such method. split() 就是这样一种方法。 String tokenizer is one such class that does the same.字符串标记器就是这样一个类。 You can read more about them on java docs.您可以在 java 文档上阅读更多关于它们的信息。

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.将“7-H”之类的参数拆分为“7”和“H”后,您可以使用类似 parseInt() 方法的方法直接将 Integer 解析为字符串。 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.现在您已将“7”转换为 7,您可以使用替换或其他方式将“H”替换为其等值数。

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 .在作业中,假设您必须制作两个由main功能组成的PlayingCards类,因此它将是 runner 类和Card ,它将有两个整数成员ranksuit
  • The input will be a string in the form 7-H 4-S AS KD , where each the card is separated by a space.输入将是格式为7-H 4-S AS KD的字符串,其中每张卡片由空格分隔。
  • The task is to convert each card into a Card object任务是将每张卡片转换为Card对象

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"] .拆分后,数组应类似于["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现在,切换rank-stringsuit-string以获得ranksuit
  • Finally, Create Card object using the rank and suit最后,使用ranksuit创建Card对象

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没有split()函数的拆分字符串

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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