在数组中输入两次相同的数字

时间:2013-06-10 03:15:13

标签: java arrays list loops

任何可能的方式来保持输入数字,当输入相同的数字2次或更多次出现错误信息或类似的东西?我只需要用Java来回答这个问题。我是新人,我不知道从哪里开始。我需要帮助搜索数组中的值,然后打印出已输入的所有数字。

public class Test 
{
 public static void main(String args[])
 {

  Scanner input = new Scanner(System.in);
  System.out.println("How big is the group?: ");
  int[] group = new int[input.nextInt()];



for (int i = 0; i < group.length; i++)
{
    System.out.println("Please enter number: ");
    group[i] = input.nextInt();
}           

2 个答案:

答案 0 :(得分:1)

我认为这就是你要找的东西。在for循环内部,有一个while循环旋转以继续收集新的int,直到你输入一个尚未在列表中的那个。

for (int i = 0; i < group.length; i++)
{
    System.out.println("Please enter number: ");
    int next = input.nextInt();

    while(Arrays.asList(group).contains(next)) {  // Keep asking for new input while the input is already in list
        System.out.println("That number is already in the group ... try again.");
        next = input.nextInt();
    }

    group[i] = next;
}  

答案 1 :(得分:1)

由于这显然是一种“学习练习”,因此只提供一些提示:

  1. 您可以通过逐步检索数组索引并测试每个索引处的元素来搜索数组。

  2. 方法和类都需要关闭} ...


  3.   

    我只需要用Java解答这个问题。

    这是不正确的。你真正需要的是一些提示。如果我们为您提供Java代码,您就会错过自己编写的重要学习经历。这就是作业的全部要点。如果你不相信我,去问你的老师。