I'm creating a lottery program, and I used a set class I created instead of the java set.
Heres's my Set class; it does the basic functions of a Java set
import java.util.*;
public class mySet<T>
{
private Set<T> yourSet=new HashSet<T>();
T number;
mySet()
{
}
private mySet(Set<T> yourSet)
{
this.yourSet=yourSet;
}
public void print()
{
if(isEmpty())
System.out.println("Your set is empty");
else
System.out.println(yourSet);
}
//public
public void addToSet(T number)
{
this.number=number;
yourSet.add(number);
}
public boolean isEmpty()
{
return (yourSet==null);
}
public int getCardinality()
{
int size=0;
size=yourSet.size();
return(size);
}
public void clear()
{
yourSet.clear();
}
public boolean isInSet(int value)
{
if(isEmpty())
{
System.out.println("The set is empty");
}
else
{
yourSet.contains(value);
return true;
}
return false;
}
public mySet <T>intersection(mySet<T> setb)
{
Set<T> newSet=new HashSet<>(yourSet);
newSet.retainAll(setb.yourSet);
return new mySet<>(newSet);
}
}
Here's the program that gets and validates the user's input
public mySet userLottery(mySet userStore){
for (int x=0;x<6;x++)
{
int user=getUser("Please enter your lottery number : ");
if(userStore.isInSet(user) )// checks if the number entered by the user have been entered before
{
x--;
System.out.println("No duplicates are allowed");
continue;
}
else if (user>=LOTTERY_MAX )// checks if the user entered a number that is higher than the Lottery max
{
x--;
System.out.println("The value you entered must be lower than the limit "+"("+LOTTERY_MAX+")");
continue;
}
else if (user<1 )//prevents the user from entering a number less than 1
{
x--;
System.out.println("The value you entered must be greater than 0");
continue;
}
else
{
userStore.addToSet(user);// adds the users input to the Set if it meets all conditions
}
}
System.out.println("this is the users input : "+userStore);//prints out the users input
return userStore;
}
LOTTERY_MAX
is the maximum range of the lottery number, and the user selects the range.
When I run the program and input numbers, it prints out no duplicates allowed, and it's stuck in an infinite loop somehow. I tried clearing the set from the start, but the same issue continues. When I removed the if statements, the program runs as expected, but then there is nothing to validate the user's input. The program is meant to take user input put it in a set, cross-check it against a set of computer-generated numbers.
public boolean isEmpty()
{
return (yourSet==null);
}
this is not how you would check if your set is empty or not. This is how you'd like to do it:
public boolean isEmpty()
{
return (yourSet==null || yourSet.isEmpty());
}
EDIT: I don't understand why you are wrapping HashSet
instead using it directly. You would have avoided so many problems if you did that. Those classes exist for a reason. Learn to utilize them properly.