我想创建一个抽奖程序,创建四个随机数,每个数在0到9之间(含)。该程序要求用户猜测四个数字并将每个用户猜测与四个随机数进行比较,并将赢得的消息显示为:
No matches 0 points
Any one digit matching 5 points
Any two digits matching 100 points
Any three digits matching 2,000 points
All four digits matching 1,000,000 points
我的程序运行但它有一些逻辑错误。例如,输出应为:
Random numbers:2 3 3 4
Guess numbers: 1 2 5 7-->1 matching digit
Guess numbers: 3 5 7 3-->2 matching digits
Guess numbers: 3 3 3 1-->2 matching digits
Guess numbers: 3 3 3 3-->2 matching digits
public class Lottery
{
public static void main(String[] args) {
final int LIMIT=10;
int totalCount=0;
int totalPoint;
Random random=new Random(); //creating object of random class
Scanner input=new Scanner(System.in);//creating object of scanner class
//declaring two arrays
int[] guessNumber= new int[4];
int[] randomNumber=new int[4];
for(int i=0;i<4;i++)
{
randomNumber[i]=random.nextInt(LIMIT);//returns value between 0 to 9(inclusive)
}
for(int i=0;i<4;i++)
{
System.out.println("Enter your first guess number from 0 to 9:");
guessNumber[i]=input.nextInt();
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (randomNumber[i] == guessNumber[j])
{
++totalCount;
break;
}
}
}
if(totalCount == 1)
{
totalPoint=5;
}
else if(totalCount == 2)
{
totalPoint=100;
}
else if(totalCount == 3)
{
totalPoint=2000;
}
else if(totalCount == 4)
{
totalPoint=100000;
}
else
{
totalPoint=0;
}
//dispalying points
System.out.println("You have earned " +totalPoint+ "points!!");
}
}
答案 0 :(得分:0)
看起来你的整体逻辑很好。 如果我理解正确,你只需要一个不同的输出。 使用类似的东西输出。
String guessNumbers = "";
String randomNumbers = "";
for (int i = 0; i < 4; i++){
randomNumbers += randomNumber[i]+" ";
guessNumbers += guessNumber[i]+" ";
}
System.out.println("Random numbers: "+randomNumbers);
System.out.println("Guess numbers: "+guessNumbers+" --> # of matching digits "+totalCount);
System.out.println("You have earned " +totalPoint+ " points!!");
这就是它现在打印的内容:
Random numbers: 2 9 7 4
Guess numbers: 7 4 5 2 --> # of matching digits 3
You have earned 2000 points!!
答案 1 :(得分:0)
在我看来,问题在于,一旦你匹配了一个特定的数字,你就应该将它从流通中删除,这样多个相同价值的猜测就不算作匹配。一种解决方案是为randomNumber
使用ArrayList,并在匹配时删除它们。如果您使用以下内容替换// declaring two arrays
评论和totalPoint
作业之间的内容,则可能会根据您的示例执行您所要求的操作。
int guess;
ArrayList<Integer> randomNumber = new ArrayList<Integer>();
for (int i = 0; i < 4; i++) {
randomNumber.add(random.nextInt(LIMIT));
}
for (int i = 0; i < 4; i++) {
System.out.print("Enter your guess number from 0 to 9: ");
guess = input.nextInt();
for (int j = 0; j < randomNumber.size(); ++j) {
if (randomNumber.get(j) == guess) {
++totalCount;
randomNumber.remove(j);
break;
}
}
}
input.close();
请注意,我已经选择在读取时处理每个猜测,而不是将它们存储在数组中并稍后处理它们。