2016-10-04 63 views
0

到目前爲止,我的程序已經算出來了,這只是我不理解我給出的這些指令(或者至少知道如何去做)。使用switch語句玩撲克牌程序(Java)

當我輸入10時,它打印出「10」,但是當我嘗試爲10個黑桃輸入10S時,它只打印出「黑桃」。

希望這裏有人能給我是溶液或點我就如何解決我的問題的正確方向:

使用switch語句的結果賦給變量的初始值 - 的價值卡

使用第二個switch語句來連接到結果變量卡的套裝」

這裏是代碼:

import java.util.*; 


public class CardConverter { 

    public static void main(String[] args) { 
     Scanner keyboard = new Scanner(System.in); 

     //will hold string that user will input 
     String card, face, suit, result; 

     //getting input from user and telling them correct format 
     System.out.println("Please enter either the number or face value intial of a card followed by the initial of it's suit (ie. QH for Queen of Hearts)"); 
     card = keyboard.nextLine(); 
     //gets first value 
     face = card.substring(0); 
     //sets substring for 10 only 
     //substring for after all single digit/letter card faces 
     suit = card.substring(1); 


     //to print face and word of 
     switch (face) 
     { 
     case "10": 
      System.out.println("10 of "); 
      break; 
     case "2": 
      System.out.println("2 of "); 
      break; 
     case "3": 
      System.out.println("3 of "); 
      break; 
     case "4": 
      System.out.println("4 of "); 
      break; 
     case "5": 
      System.out.println("5 of "); 
      break; 
     case "6": 
      System.out.println("6 of "); 
      break; 
     case "7": 
      System.out.println("7 of "); 
      break; 
     case "8": 
      System.out.println("8 of "); 
      break; 
     case "9": 
      System.out.println("9 of "); 
      break; 
     case "J": 
      System.out.println("Jack of "); 
      break; 
     case "Q": 
      System.out.println("Queen of "); 
      break; 
     case "K": 
      System.out.println("King of "); 
      break; 
     case "A": 
      System.out.println("Ace of "); 
      break; 
     } 
     //to print out card suit 
     switch (suit) 
      { 
      case "H": 
        System.out.println("Hearts"); 
       break; 
      case "C": 
       System.out.println("Clubs"); 
       break; 
      case "S": 
       System.out.println("Spades"); 
       break; 
      case "D": 
       System.out.println("Diamonds"); 
       break; 
     } 
    } 
} 
+0

提示:'card.substring(0);'給你什麼樣的價值?案件陳述中是否有任何內容? –

回答

1

你的問題開始於card.substring(0);,這等於card,因爲從字符串的開始的子字符串。也許你想要card.charAt(0);?但是這也是錯誤的,因爲"10S"將有三個字符,兩個用於面值。

您需要專門處理三個字符的輸入,或者對substring -ing更聰明。

你知道訴訟將永遠是最後一個字符,所以使用該字符串的長度爲charAt

int suitIndex = s.length() - 1; 
String suit = ""+s.charAt(suitIndex); 
String face = s.substring(0,suitIndex); 

您還可以簡化案件

case "J": 
    System.out.println("Jack of "); 
    break; 
case "Q": 
    System.out.println("Queen of "); 
    break; 
case "K": 
    System.out.println("King of "); 
    break; 
case "A": 
    System.out.println("Ace of "); 
    break; 
default: 
    System.out.println(face + " of "); // handle all the numbers 
    break; 
+0

您的建議實際上是完美的解決方案,非常感謝 – MZiskaO