从字符串中获取数字(15米)

时间:2013-10-30 03:14:07

标签: java

好吧所以我要做的是,在这个名为Minecraft的游戏中,如果他们键入15h,则意味着15小时,或20分钟,20分钟。所以这就是我想出来的。

String time = args[3];//args[3] is the text they write (15m, 1d, 20h)
            time = time.replace("m", " minutes.");
            time = time.replace("h", " hours.");
            time = time.replace("d", " days.");
            if(time.contains("m"))
            {
                //Convert the minutes into seconds
                                    //In order to do that I have to pull out the number from "15m", so I would have to pull out 15, how would I do that?
            }

2 个答案:

答案 0 :(得分:2)

您可以使用java.util.Scanner类。

Scanner s = new Scanner(args[3]);
while (s.hasNextInt()) {
    int amount = s.nextInt();
    String unit = s.next();
    if ("m".equals(unit)) {
        // handle minutes
    } else if ("h".equals(unit)) {
        // handle hours
    } else if ("d".equals(unit)) {
        // handle days
    } else {
        // handle unexpected input
    }
}

答案 1 :(得分:1)

您可以使用Regex提取数值。

Pattern p = Pattern.compile("^[a-zA-Z]+([0-9]+).*");
Matcher m = p.matcher(time);

if (m.find()) {
   System.out.println(m.group(1));
}