我在這裏有一個程序,這真的讓我很困惑(主要是因爲我嘗試了不同的方法來使它工作,並且遇到了某種錯誤每次)。我應該創建一個程序,通過隨機生成6個數字並讓用戶輸入6個自己選擇的數字來模擬真實生活中的彩票。現在該程序應該對這兩個數組進行線性搜索,並查看用戶的任何數字是否等於隨機生成的數字,但我被教導使用線性搜索的方式不包括一次搜索多個數字(即使用數組),我因此困惑如何返回一個整數,如果大於零,打印「你贏了」的聲明,如果小於零打印,「你已經失去了聲明」。如何在彩票程序中對數組進行線性搜索
import java.util.*;
import java.text.*;
public class Lotto649 {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
int [] playernums = new int [6];
int [] usernums = new int [6];
int [] result = new int [6];
int verdict;
int index;
System.out.printf ("Play Lotto 649 %n%n");
// Get randomly generated numbers from method and add them to array 'result'
result = GenerateLotto (playernums);
// get 6 numbers from user
for (int j = 0; j < usernums.length; j++){
System.out.printf ("Please enter a number between 1 and 49: ");
usernums[j] = s.nextInt();
}
// Print the winning numbers that were randomly generated
for (int i = 0; i < result.length; i++){
System.out.printf ("The winning Lotto 649 numbers are: " + result[i] + ", ");
}
}
// Method to fill array with winning lottery numbers
public static int [] GenerateLotto (int [] a){
Random g = new Random();
// fill array with 6 randomly generated numbers
for (int i = 0; i < a.length; i++){
a[i] = g.nextInt (49) + 1;
}
return a;
}
index = find (playernums,results);
// int [] A is player nums (player chosen numbers)
// int [] B is results array (RNG numbers)
public static int find (int[] A, int[] B){
for (int index = 0; index < A.length; index++){
for (int index2 = 0; index2 < B.length; index2++){
if (A[index] == B[index2])
return index;
}
}
}
}
我已經停止了現在的代碼搞亂了,因爲我覺得我會進一步打破它。
哇,謝謝。你甚至可以改進這些小問題。好評如潮! ...我首先需要15個聲望,哈哈。 – selereth 2015-03-31 19:08:49