【发布时间】:2021-07-29 21:18:36
【问题描述】:
我正在创建一个彩票程序,并且我使用了我创建的集合类而不是 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 语句时,程序按预期运行,但是没有任何东西可以验证用户的输入。该程序旨在将用户输入放入一组中,并与一组计算机生成的数字进行交叉检查。
【问题讨论】:
-
mySet 有几个错误。可能 isEmpty 是错误的,您的集合可以是非 null 并且仍然为空。 isInSet 不检查包含的返回,它总是返回 true。所以我怀疑你的集合是空的但不是空的,所以 isEmpty() 返回 false,这导致 isInSet 总是返回 true。
-
(1) 你应该使用适当的缩进,(2) 当集合不为空时,你的
mySet.isInSet函数总是返回true。它实际上并不检查提供的值是否在集合中。 (3) 更新for循环计数器是不好的做法(即x--的事情)。 (4) 你应该尝试用调试器跟踪这个东西。 -
x--;为什么要减少变量?您还应该学习在 IDE 中使用自动格式化程序。 -
@MattClark 因为他们想要 6 个数字,因此减少 x 以表明此输入“不计入”,因为它有问题。
-
从您提供的一些细节来看,
getUser可能是罪魁祸首,但您没有粘贴该代码。
标签: java validation user-input infinite-loop