繁体   English   中英

如何将6个整数的数组与2个整数的数组[19] [5]进行比较?

[英]How can I compare an array of 6 ints to a 2d array of ints [19][5]?

我正在为一所学校的项目工作,无法解决这个问题。 我是一个非常初级的初学者。

我有一个名为tickets[19][6]的二维阵列tickets[19][6] 20张票,每张票6张。 我试图将这20张票与常规的一组int与6个号码进行比较,这些号码叫做winner[5] ,我从.txt文件中读取。

两个阵列都陈述如下:

public static int[] winner = new int[5]
public static int[][] tickets = new int[19][5]

请记住,我对此很新,我提前感谢您的帮助!

编辑这是我用来将用户输入分配给我的2d数组的循环,只是在我完成整个事情时意识到这是一个无限循环。 我认为编写代码会更多......好吧,写作! 到目前为止似乎更像是调试的艺术。

static void ticketNumberArray(){

    int number = 1;        // which of the six numbers you need from the ticket
    int ticketCount = 1;   // which ticket (out of 20) you are currently on

    while(ticketCount<21){ // sentinel controlled while loop,
                           // will continue until the twentieth ticket is entered
        System.out.println("Please type number " +number+ " of ticket number " +ticketCount+ ".");
                           //asks for the numbers of the ticket your currently on

        Scanner keyboard = new Scanner(System.in); // initiates a scanner variable

        int ticketNumber = keyboard.nextInt();     // assigns user input to the double variable ticketNumber
                                                   // and initializes as a double

        tickets[ticketCount-1][number-1]=ticketNumber;  // assigns user input into a 2-d array

        number++;           //Sentinel variable

        if(number==7){      //loop that controls the ticket count, every 6 numbers ='s one ticket
            ticketCount++;
            number=1;
        }
    }
}

首先,声明数组时放在[ ]的数字是数组的大小。 因此,要制作包含六个项目的数组,您需要输入[6] 索引将编号为0 - > 5。

您只需要在tickets数组中循环票证“行”,并将其与获胜者数组进行比较。 每行都是一张无形的票。 2D阵列中的“列”将是构成票证的各个麻木。

如果票证中各个号码的顺序很重要,您可以使用Louis的建议与Arrays.equal (即如果获胜者为0-1-2-3你只能赢得0-1-2-30-1-2-3 - 大多数彩票允许你赢得任何组合。)

for(int i=0; i < tickets.length; i++)
{
   int[] ticket = tickets[i];

   if(Arrays.equals(ticket, winner))
   {
      // This one is the winner

      // For efficiency you should probably stop looping
      break;
   }
}

编辑:

当学生使用API​​时,很多介绍教授都不喜欢它。 所以,你必须写自己的equals函数。

private static boolean areEqual(int[] a, int[] b)
{ 
   if(a == null && b == null)
       return true;

   // Not equal if one is null and the other is not     
   if(a == null || b == null)
       return false;

   if(a.length != b.length)
       return false;

   // When we get here we have to check each element, one by one
   // Implementation left as exercise :-)
}

门票有5个整数,还是6个? 你的问题与自己相矛盾。

无论如何,如果你只想检查故障单中的整数是否匹配 - 如果它们的顺序完全相同 - 最简单的解决方案就是使用Arrays.equals(int[], int[])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM