指派的链接: 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
编辑:
我在最后添加了一个新方法来比较数字,但问题是它在一般情况下比较它们而不是从位置到位置。这似乎是现在的主要问题。
答案 0 :(得分: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数组中输入1中有两个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