我是java的新手,我正在尝试向用户询问输入,但我不希望用户能够输入两次相同的数字。这就是我的尝试
g1 = iBox.getInteger("Enter your 1st number");
g2 = iBox.getInteger("Enter your 2nd number");
if(g1 == g2){
g2 =iBox.getInteger("Number used, please re-enter");
}
g3 = iBox.getInteger("Enter your 3rd number");
if(g3 == g1){
g3 =iBox.getInteger("Number used, please re-enter");
}
else if(g3 == g2){
g3 =iBox.getInteger("Number used, please re-enter");
}
g4 = iBox.getInteger("Enter your 4th number");
if(g4 == g1){
g4 =iBox.getInteger("Number used, please re-enter");
}
else if(g4 == g2){
g4 =iBox.getInteger("Number used, please re-enter");
}
else if(g4 == g3){
g4 =iBox.getInteger("Number used, please re-enter");
}
oBox.print(" " + g1 + " " + g2 + " " + g3 + " " + g4 + " ");
答案 0 :(得分:3)
你应该使用循环和集合。 伪代码:
let S be the set of used numbers(or array, if order is important)
clear contents of S
for I = 1 to N, where N is the number of numbers you want to get
int g = iBox.getInteger("Enter Ith number");
while(S.contains(g))
g = iBox.getInteger("Number used, please re-enter");
Add g into S.
答案 1 :(得分:1)
ArrayList
ArrayList
contains()
以检查list
答案 2 :(得分:1)
我建议将以前的输入存储在List
或某种集合中。然后,您可以使用.contains(Object o)
方法查看集合是否已包含特定值。
这将允许您将应用程序扩展到固定数量的输入之外。