【问题标题】:Convert String to int inside "if" statement在“if”语句中将 String 转换为 int
【发布时间】:2013-01-20 03:39:01
【问题描述】:

我正在学习我的 Intro Java 编程课程,想知道在if 语句中是否有我想要做的事情的捷径。

基本上,我的程序接收扑克牌的两个字符缩写并返回完整的牌名(即“QS”返回“黑桃皇后”。

现在我的问题是: 当我为编号为 2-10 的卡片编写 if 语句时,我需要为每个数字单独声明还是可以将它们组合成一个 if 语句?

检查我的代码在哪里说 IS AN INTEGER(显然不是 Java 表示法。)这是我要澄清的代码片段:

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the card notation: ");
        String x = in.nextLine();
        if (x.substring(0,1).equals("A")){
            System.out.print("Ace");
        }
        else if(x.substring(0,1) IS AN INTEGER) <= 10)){   // question is about this line
            System.out.print(x);
        }
        else{
            System.out.println("Error.");
        }
    }
}

【问题讨论】:

  • 你输入“黑桃十”是“10S”还是“TS”?
  • 应该是 10S,任何转换为​​ char 的尝试都会抛出一个曲线球
  • 所以任何花色的10是三个字符的缩写?

标签: java string if-statement integer int


【解决方案1】:

你可以这样做:

    char c = string.charAt(0);
    if (Character.isDigit(c)) {
        // do something
    }

x.substring(0,1)string.charAt(0) 几乎相同。区别在于 charAt 返回 char 而 substring 返回 String

如果这不是家庭作业,我建议您改用StringUtils.isNumeric。你可以说:

    if (StringUtils.isNumeric(x.substring(0, 1))) {
        System.out.println("is numeric");
    }

【讨论】:

  • 谢谢,我认为第一个就足够了。我想如果我为此使用单独的 IF 语句,我将能够解决 10 个问题。为快速响应点赞^-^
【解决方案2】:

另一种将字符串转换为 int 的方法是:

Integer number = Integer.valueOf("10");

您可能考虑的另一种方法是使用类或枚举。

public class Card {
    // Feel free to change this
    public char type; // 1 - 10, J, Q, K, A
    public char kind; // Spades, Hearts, Clubs, Diamonds

    public Card(String code) {
        type = code.charAt(0);
        kind = code.charAt(1);
    }

   public boolean isGreaterThan(Card otherCard) {
       // You might want to add a few helper functions
   }
}

【讨论】:

    【解决方案3】:

    这是我能想到的最简洁的解决方案:

    private static Map<String, String> names = new HashMap<String, String>() {{
        put("A", "Ace"); 
        put("K", "King"); 
        put("Q", "Queen"); 
        put("J", "Jack"); 
    }};
    

    然后在你的主要:

    String x = in.nextLine();
    if (x.startsWith("10")) { // special case of two-character rank
        System.out.print("Rank is 10");
    } else if (Character.isDigit(x.charAt(0)){
        System.out.print("Rank is " + x.charAt(0));
    } else
        System.out.print("Rank is: " + names.get(x.substring(0,1));
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 2015-11-09
      • 1970-01-01
      • 2019-04-09
      • 2023-04-08
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多