我正在创建一个彩票程序,我使用了我创建的集合类而不是java集合。
这是我的Set课程;它完成Java集的基本功能
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);
}
}
以下是获取并验证用户输入的程序
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
是彩票号码的最大范围,并且用户选择该范围。
当我运行程序并输入数字时,它不允许打印出重复的数字,而且不知何故,它陷入了无限循环。我从一开始就试图解围,但同样的问题还在继续。当我删除if语句时,程序按预期运行,但没有任何东西可以验证用户的输入。该程序旨在接受用户输入,将其放入一组中,并与一组计算机生成的数字进行交叉检查。
public boolean isEmpty()
{
return (yourSet==null);
}
这不是检查集合是否为空的方法。这就是你想要做的:
public boolean isEmpty()
{
return (yourSet==null || yourSet.isEmpty());
}
编辑:我不明白你为什么包装HashSet
而直接使用它。如果你那样做的话,你会避免那么多问题的。这些类的存在是有原因的。学会正确利用它们。