0

作业链接:http: //i.imgur.com/fc86hG9.png

我在辨别如何获取一系列数字并将它们应用于没有循环的数组时遇到了一些麻烦。不仅如此,我在比较它们时也遇到了一些麻烦。到目前为止我写的是:

import java.util.Scanner;

public class Lottery {

public static void main(String[] args) {
 int userInputs[] = new int[5];
 int lotteryNumbers [] = new int[5];
 int matchedNumbers =0;
 char repeatLottery = '\0';


    Scanner in = new Scanner (System.in);

    do{
        System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
            for(int i = 0; i <5; i++ )
            userInputs[i] = in.nextInt();

            System.out.println("Your inputs: ");
            printArray(userInputs);

        System.out.println("\nLottery Numbers: ");
        readIn(lotteryNumbers);
        for(int i=0; i<5; i++) {
            System.out.print(lotteryNumbers[i] + " ");
        }

        matchedNumbers = compareArr(userInputs, lotteryNumbers);

        System.out.println("\n\nYou matched " + matchedNumbers + " numbers");



        System.out.println("\nDo you wish to play again?(Enter Y or N): ");
         repeatLottery = in.next().charAt(0);
    }
    while (repeatLottery == 'Y' || repeatLottery == 'y');

}
public static void printArray(int arr[]){

    int n = arr.length;

    for (int i = 0; i < n; i++) {
        System.out.print(arr[i] + " ");
    }
}

public static void readIn(int[] List) {
    for(int j=0; j<List.length; j++) {
        List[j] = (int) (Math.random()*10);
    }
}

public static int compareArr (int[] list1, int[] list2) {
    int same = 0;
    for (int i = 0; i <= list1.length-1; i++) {
        for(int j = 0; j <= list2.length-1; j++) {
            if (list1[i] == list2[j]) {
                same++;


            }

        }
    }
    return same;
}

}

您会注意到,我注释掉了输入行,因为我不太确定如何处理它。如果我将它们放在一个数组中,我认为我应该能够相当容易地比较它们。这是我们的第一个分配处理数组,我认为它似乎有点深入,因为它只有一个课时;所以,请原谅我的无知。:P

编辑:

我在最后添加了一个新方法来比较数字,但问题是它一般比较它们,而不是从一个位置到另一个位置。这似乎是现在的主要问题。

4

1 回答 1

1

你的问题不是 100% 清楚,但我会尽力而为。1-我没有看到读取用户输入的任何问题

int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
 userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure

编辑:在您共享的关于分配的链接中很重要,比较需要检查值和位置,因此如果在 loterry 数组中的输入一个中有两个 5 一,它们需要在同一位置再次检查分配

// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
   if ( userInput[i] == loterryArray[i] )
       result++
}
// in this comparsion if the digits are equale in value and location result will be incremented  
于 2013-03-28T00:50:13.773 回答