2013-03-28 56 views
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

编辑:

我在结尾加上一个新的方法来比较数字,但问题是他们,一般比较,而不是从位置到位置。这似乎是现在的主要问题。

+0

注释掉部分应该已经是正确的写出来呢?然后循环并比较两个数组。 – Patashu 2013-03-28 00:35:31

+0

所以你不允许使用for循环来设置数组的值?是这样吗?目前还不清楚你的问题是什么。 – ktm5124 2013-03-28 00:36:52

回答

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 

编辑:在链接重要的是你对分配共享的比较需要检查的价值和位置,这样如果有两个5之一输入一个在他们需要在同一个位置loterry阵列检查分配再次

// 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 
+0

比较奏效。我创建了一个返回结果的int方法。谢谢! – TheFoundry 2013-03-28 00:58:02

+0

编辑:重要,,,,,,在你分享的关于分配的链接比较需要检查的价值和位置,所以如果有两个5输入一个在loterry数组他们需要在同一个位置检查再次分配 – 2013-03-28 00:59:53