如何在Java中将字符串转换为int? [英] How do you convert from a string to an int in Java?

查看:191
本文介绍了如何在Java中将字符串转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我必须创建一个卡片项目,它接受一个字符串,如Six of Hearts,并根据数字(六)和套装(心)的值将其转换为整数数组。关于如何让java取字符串six并输出6 ......任何提示我都会碰壁?

So I have to make a card project that takes a string such as "Six of Hearts" and converts that into an integer array based on the value of the number (six) and the suit (hearts). I'm hitting a wall as to how to get java to take the string "six" and output 6... Any hints?

编辑:
俱乐部= 0;
黑桃= 3;
Hearts = 2;
钻石= 1;

Clubs = 0; Spades = 3; Hearts = 2; Diamonds = 1;

推荐答案

这通常是您使用enum的内容:

This is typically something you would use an enum for:

enum Suit{
 CLUBS   ("clubs", 0),
 DIAMONDS("diamonds", 1),
 HEARTS  ("hearts", 2),
 SPADES  ("spades", 3);

 private final String name;
 private final int value;
 private static final HashMap<String, Suit> suitByName;
 static {
    suitByName = new HashMap<String, Suit>();
    for (Suit s: Suit.values()){
        suitByName.put(s.name, s);
    }
 }

 Suit(String name, int value){
     this.name = name;
     this.value = value;
 }
 public int getValue(){
    return this.value;
 }

 public static Suit fromString(String card){
    return suitByName.get(card.toLowerCase());
 }
}

省略卡值的代码。遵循相同的方法。

Code for card values omitted. Follows the same approach.

这篇关于如何在Java中将字符串转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆