[英]Taking User Input for an Array
作業鏈接: 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
編輯:
我在末尾添加了一種新的方法來比較數字,但是問題是它在一般情況下而不是從位置到位置比較它們。 這現在似乎是主要問題。
您的問題不是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
編輯:在您共享的關於分配的鏈接中很重要,比較需要檢查值和位置,因此,如果在洛里數組中輸入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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.