m bunn m bunn - 2 months ago 6
Java Question

How to concatonate two string variables into a result string, after using switch case method to determine new result in java?

So here is a link to another persons question and its my exact assignment.

Concatenating Switch Statements for Playing Cards Assignment

How can I get my result string to display the valueofCard then the suitofCard in this format "value of suit"
Also, how can I shorten up the 2-10 value range within a switch case?
I am aware I have " of " and a couple other lines that make no sense, I just figured I am missing something big anyways.
Thanks for any help, have lots of catching up to do.

System.out.print("Please enter a letter/integer of a playing card (A, J, Q, K, or 2 - 10),\nfollowed by card type (D, H, S, C):");
Scanner kbd = new Scanner(System.in);
String userInput = kbd.nextLine();
String valueofCard = userInput.substring(0, userInput.length() / 2); // gives first half of string
String suitofCard = userInput.substring(userInput.length() / 2); //give last half of string with + 1 if odd
StringBuilder result = new StringBuilder();

switch (valueofCard) {
case "A":
result.append("Ace of ");
break;
case "J":
result.append("Jack of ");
break;
case "Q":
result.append("Queen of ");
break;
case "K":
result.append("King of ");
break;
case "2":
result.append("2 of ");
case "3":
result.append("3 of ");
case "4":
result.append("4 of ");
case "5":
result.append("5 of ");
case "6":
result.append("6 of ");
case "7":
result.append("7 of ");
case "8":
result.append("8 of ");

case "9":
result.append("9 of ");
case "10":
result.append("10 of ");
break;
}

switch (suitofCard) {
case "D":
result.append("Diamonds");
break;
case "H":
result.append("Hearts");
break;
case "S":
result.append("Spades");
break;
case "C":
result.append("Clubs");
break;
}

System.out.println(result.toString());

kbd.close();
}


}

Answer

Option 1 - You could use a Stringbuilder to do this.

StringBuilder cardAndSuit = new StringBuilder();

    switch (valueofCard) {
        case "A":
            cardAndSuit.append("Ace of");
    .....


     switch (suitofCard) {
        case "D":
             cardAndSuit.append("Diamonds");
            break;   
    ...

    // Print the final string
    System.out.println(cardAndSuit.toString()); // Ace of Diamonds

Option 2 - You could also just create a regular String and append to it.

String cardAndSuit = '';
cardAndSuit += "Ace of";
cardAndSuit += " Diamonds";
System.out.println(cardAndSuit); // Ace of Diamonds

2 is probably easier and more terse. Option 2 will actually be turned into option 1 by the compiler behind the scenes.