首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在"if“语句中将字符串转换为int

在"if“语句中将字符串转换为int
EN

Stack Overflow用户
提问于 2013-01-20 03:39:01
回答 3查看 5.7K关注 0票数 0

我正在继续学习我的Intro编程课程,并想知道我在if语句中所做的工作是否有捷径。

基本上,我的程序收到一张扑克牌的两个字符的缩写,并返回全卡名(."QS“返回”黑桃皇后“()

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

检查我的代码在哪里显示是整数(显然不是符号)。下面是我的代码片段以澄清:

代码语言:javascript
运行
复制
    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.");
        }
    }
}
EN

回答 3

Stack Overflow用户

发布于 2013-01-20 03:42:35

你可以这样做:

代码语言:javascript
运行
复制
    char c = string.charAt(0);
    if (Character.isDigit(c)) {
        // do something
    }

x.substring(0,1)string.charAt(0)几乎一样。区别是charAt返回一个char,子字符串返回一个String

如果这不是作业,我建议你用StringUtils.isNumeric代替。你可以说:

代码语言:javascript
运行
复制
    if (StringUtils.isNumeric(x.substring(0, 1))) {
        System.out.println("is numeric");
    }
票数 5
EN

Stack Overflow用户

发布于 2013-01-20 03:46:13

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

代码语言:javascript
运行
复制
Integer number = Integer.valueOf("10");

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

代码语言:javascript
运行
复制
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
   }
}
票数 1
EN

Stack Overflow用户

发布于 2013-01-20 03:45:45

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

代码语言:javascript
运行
复制
private static Map<String, String> names = new HashMap<String, String>() {{
    put("A", "Ace"); 
    put("K", "King"); 
    put("Q", "Queen"); 
    put("J", "Jack"); 
}};

然后在你的主旋律里:

代码语言:javascript
运行
复制
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));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14421461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档