试图做一个彩票游戏,比较用户输入到随机生成的存储彩票答案的数组(不工作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
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – slim
很难回答不知道你所期望的程序做什么实际的问题,取而代之。 –