gpt4 book ai didi

java - 获取数组的用户输入

转载 作者:行者123 更新时间:2023-12-01 14:43:48 25 4
gpt4 key购买 nike

作业链接: /image/utlLG.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;
}

}

正如您所注意到的,我注释掉了输入行,因为我不太确定如何处理它。如果我将它们放在一个数组中,我想我应该能够相当容易地比较它们。这是我们的第一个作业处理数组,我认为对于只有一个类(class)周期来说它似乎有点深入;所以,请原谅我的无知。 :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

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

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

关于java - 获取数组的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15672171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com