Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

How do you convert from a string to an int in Java?

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a Map. You could also use a case or if else statements to accomplish this.

    HashMap<String, Integer> numbers = new HashMap<String, Integer>();
    numbers.put("ace", 1);
    numbers.put("two", 2);
    numbers.put("three", 3);
    numbers.put("four", 4);
    numbers.put("five", 5);
    numbers.put("six", 6);
    numbers.put("seven", 7);
    numbers.put("eight", 8);
    numbers.put("nine", 9);
    //etc...
    HashMap<String, Integer> suits = new HashMap<String, Integer>();
    suits.put("clubs", 0);
    suits.put("spades", 3);
    suits.put("hearts", 2);
    suits.put("diamonds", 1);

    numbers.get("zero");//use this to access the number
    suits.get("spades");//use this to access the suit

Case sensitivity will matter here so make sure the key matches whatever you pass to access the value...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...