Java:我如何测试是否有匹配的序列号?

时间:2015-07-14 06:22:55

标签: java regex

我正在制作抽奖活动计划,根据该人的6位数票号与6位中奖号码的匹配程度,可以获得多个奖品。

如果中奖号码中的3个连续号码与该人票的3个连续号码匹配,则可获得其中一个奖品。

示例:如果机票上的号码是123456,如果获胜号码在位置1 - 3中有123,在位置2 - 4中有234,在位置3 - 5中有345,或者在位置4中有456,则为赢家6。

我想知道如何通过彩票号码/门票进行此操作?

2 个答案:

答案 0 :(得分:0)

您可以使用模运算一次测试3位数,然后重复除以10来测试不同的3位数组:

static boolean match3(int ticket, int winner)
{
    for(int i = 0; i < 4; i++)
    {
        if((ticket % 1000) == (winner % 1000))
            return true;
        ticket /= 10; winner /= 10;
    }
    return false;
}

假设小于6位的数字具有前导零。

答案 1 :(得分:0)

您可以使用以下逻辑来满足您的需求。

public class Test {

    public static void main(String[] args) {
        //This is containing all possible ascending combination
        String possibleComb = "0123456789"; 
        //This would be variable and will be part of your method argument
        String ticketNumber = "123456"; 

        //This loop is to get all 3 combination in only forward direction
        for(int i = 0; i < ticketNumber.length() - 1;){ 
            String tmpSubStr = ticketNumber.substring(i, i + 3);
            if(possibleComb.indexOf(tmpSubStr) == (Integer.parseInt(tmpSubStr) / 100)) {
                System.out.println("He is Lucky Customer of " + (i + 1) + "-" + (i + 3));
            }
            System.out.println();
            i = i + 3;
        }
    }
}