我试图比较不同类中的两个不同的数组,一个用用户输入的数字填充,另一个用随机填充。但我无法从用户那里得到一个填充数字的那个进入我的构造函数类来比较它们。 这是代码:
import java.util.Scanner;
class LotteryTester{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] Picks = new int [5];
System.out.println("Introduce your numbers here: ");
for(int i = 0; i < Picks.length; i++)
{
Picks[i] = input.nextInt();
}
for (int i = 0; i < Picks.length; i++)
{
System.out.println(Picks);
}
}
}
这是无法找到第一个数组的类:
import java.util.Random;
public class Lottery
{
Random random = new Random();
int number;
int count;
public Lottery( )
{
int lotteryNums[] = new int[5];
for (int i=0; i < lotteryNums.length; i++)
{
number = random.nextInt(10);
lotteryNums[i] = number;
}
}
public static int CompareNums(Picks[] numbers)
{
for (int i=0; i <Picks.length; i++)
{
if (Picks[i] == lotteryNums[i])
{
System.out.println("The number on " + (i+1)+ " matches");
count++;
}
else
{
System.out.println("the number on " + (i+1)+ " matches");
}
}
return count;
}
}
我只是不知道如何正确使用方法
答案 0 :(得分:2)
您永远不会将lotteryNums分配给构造函数之外的变量。每当方法结束时,不再可以访问在其中声明的所有变量。
你的课应该是这样的:
public class Lottery
{
Random random = new Random();
int number;
int count;
int lotteryNums[];
public Lottery()
{
lotteryNums[] = new int[5]; //Set the variable in the class so we can use it later
for (int i=0; i < lotteryNums.length; i++)
{
number = random.nextInt(10);
lotteryNums[i] = number;
}
}
public int CompareNums(Picks[] numbers) //Removed static since numbers are made in a constructor. All non-static class variables wouldn't be accessible otherwise.
{
for (int i=0; i <Picks.length; i++)
{
if (Picks[i] == lotteryNums[i])
{
System.out.println("The number on " + (i+1)+ " matches");
count++;
}
else
{
System.out.println("the number on " + (i+1)+ " matches");
}
}
return count;
}
}
然后可以更改主方法以遵循以下逻辑。 生成中奖号码:
Lottery lottery = new Lottery();
然后,询问用户他们的号码。 最后,根据中奖号码检查数字,看看用户是否赢了。
if (lottery.CompareNums(lotteryNums) == 5) System.out.println("You Won!");
答案 1 :(得分:0)
如果没有额外的类,你实际上可以做到这一点,而arrayLists会更好。
试试这个,我留下评论,告诉你我做了什么。
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class CompareArrayLists {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Integer> userNums = new ArrayList();
ArrayList<Integer> randNums = new ArrayList();
Random random = new Random();
Scanner cin = new Scanner(System.in);
int num = 0;
for (int i = 0; i < 5; i++) //let a user enter 5 numbers and generate 5 at the same time
{
System.out.print("Please enter your " + (i+1) + " number >");
num = cin.nextInt();
userNums.add(num);
num = random.nextInt(10);
randNums.add(num);
}
num = 0;
for (int j : userNums)//test each item in userNums to see if matches in randNums
{
if (!(randNums.contains(j)))
num++;//increment nums if something doesn't match
}
if (num > 0)//not a match if nums increments, you could also print nums to see how many are correct
System.out.println("Not a match");
else
System.out.println("a match");
}