簡體   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