尝试制作一个彩票游戏,将用户输入与存储彩票答案的随机生成的数据进行比较(不工作100%不确定为什么有时候它不会在答案中提取,有时会获得额外的答案.EG。总计柜台坏了?)。但是我的验证方法不正确,我不确定如何修复这个想法?
import java.util.Random;
import java.util.Scanner;
public class TestingClassDemo {
public static void main(String[] args) {
int input; //Holds keyboard input
final int TOTAL_ANSWERS = 10; //Number of answers
int[] guesses = new int[TOTAL_ANSWERS]; //Array to hold answers
//Creates a Scanner object for keyboard input
Scanner userInput = new Scanner(System.in);
//Gets the users Input
System.out.println("Welcome to the Lottery!");
for(int i = 0; i < guesses.length; i++)
{
System.out.print("Enter digit " + (i+1) + ": ");
input = userInput.nextInt();
while(!validate(guesses[i]))
{
System.out.println("Invalid input. Please enter a digit between 1-9");
System.out.print("Enter digit " + (i+1) + ": ");
input = userInput.nextInt();
}
}
//Creates a Lottery Object
TestingClass myLottery = new TestingClass(guesses);
System.out.print("\nCorrect Numbers: " + (myLottery.totalCorrect()));
}//End of Main Method
public static boolean validate(int a)
{
boolean status;
if( a == 1 || a == 2 || a == 3 || a == 4 || a == 5 || a == 6 || a == 7 || a == 8 || a == 9)
status = true;
else
status = false;
return status;
}
}//End of TestingClassDemo
其他班级
public class TestingClass {
private int[] lotteryNumbers = new int[10];
for(int i = 0; i < lotteryNumbers.length; i++)
{
lotteryNumbers[i] = (int) (Math.random()*10);
System.out.print(lotteryNumbers[i]+ " ");
}
}//End of LOOP
//Creates a Private Array for lotteryNumbers the user Guesses
private int[] lotteryGuesses = new int[10];
//Creates a Private int totalCorrect whether correct guesses are stored
private int totalCorrect = 0;
//Appends lotteryGuesses to lotteryNumbers for comparison
public TestingClass(int[] lotteryNumbers)
{
lotteryGuesses = lotteryNumbers;
}
/** Compares whether the uses LotteryGuess are correct
and if they are increases total Correct
*/
public int totalCorrect()
{
for( int x = 0; x < lotteryNumbers.length; x++)
{
if (lotteryGuesses[x] == lotteryNumbers[x])
{
totalCorrect += 1;
}
}
return totalCorrect;
}
}//End of Public Class TestingClass
答案 0 :(得分:0)
input = userInput.nextInt();
while(!validate(guesses[i]))
{
}
你在这里遗漏了一些东西。您应验证输入,并在有效时将其复制到猜测数组中。
input = userInput.nextInt();
while(!validate(input))
{
...
}
guesses[i] = input;