我创建了一个保存[24]个数据的数组,并在每个索引中分配了一些信息。我的问题是,当我想使用键盘上的Scanner调用索引时,假设我从用户那里调用了index [12],下一次我要它说时,您已经选择了该号码,请选择其他号码,等等。基本上,我不应该两次调用相同的索引,最好使用什么。
非常需要您的帮助。
答案 0 :(得分:2)
使用java.util.Set
存储选定的索引,例如java.util.HashSet
。
它应该像这样:
Set<Integer> selected = new HashSet<>();
int userInput = ...; // get input from user
while (selected.contains(userInput)) {
// print u already selected that number, choose a different number so on so forth
userInput = ...; // get input from user
}
selected.add(userInput);
// do something with the index
答案 1 :(得分:0)
必须保存选定数字的索引,然后将所有新数字与列表元素进行比较。
Scanner s = new Scanner (System.in);
int choice = s.nextInt();
List<Integer> choiced = new ArrayList<Integer>();
while (true) {//or your condition
label:
for (Integer i : choiced) {
if (choice == i) {
System.out.println("Index already selected, please select a different one");
break label;
}
}
choiced.add(choice);
choice = s.nextInt();
}
答案 2 :(得分:0)
我尝试了两种方法,但仍然可以解决,这是我的代码,您将如何应用你们在此处编写的代码。
导入java.util.Scanner;
公共类主要{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int number = 0;
String [] differentChocolate = new String[24];
differentChocolate[0] = "You receive: A star that weighs 7 grams";
differentChocolate[1] = "You receive: Praline Bag Assorted 800g";
differentChocolate[2] = "You receive: Kinder Surprise Santa 75g";
differentChocolate[3] = "You receive: Woolworths Christmas Chocolate Net Bag 72g";
differentChocolate[4] = "You receive: Quality Street Tub 726g";
differentChocolate[5] = "You receive: Cadbury Favourites Snowman Bowl 700g";
differentChocolate[6] = "You receive: Lindt Santa Pouch Bag 80g";
differentChocolate[7] = "You receive: Praline Bag Assorted 800g";
while (true){
System.out.println("Choose a chocolate (0-23): ");
number = in.nextInt();
System.out.println(differentChocolate[number]);
}
}
}