在具有用户输入的arrayList中不止一次

时间:2016-05-05 07:08:50

标签: java arraylist data-structures

在下面的代码中,我需要检查一个数字是否在ArrayList中出现多次。用户输入一个要咨询的号码,如果它存在于array并且有多个消息,则“显示多次”。我一直试图这样做,但我不知道如何。

这是main类:

    ArrayList<Integer> list = new ArrayList<>();
    list.add(3);
    list.add(2);
    list.add(7);
    list.add(2);

    System.out.println("Type a number: ");
    int number = Integer.parseInt(sc.nextLine());
    if (Metodos.moreThanOne(list, number)) {
        System.out.println(number + " appears more than once.");
    } else {
        System.out.println(number + " does not appear more than once.");
    }

这是方法:

public static boolean moreThanOne(ArrayList<Integer> list, int number) {
    for (Integer in : list) {
        if (list.contains(number) && in==in) {
            return true;
        }
    }
    return false;
}

4 个答案:

答案 0 :(得分:4)

您可以使用此代码:

if (list.lastIndexOf(element) != list.indexOf(element)) {
  return true; // you have at least two numbers
} else {
  return false; // element is not exist or you have only one element
}

答案 1 :(得分:1)

    public static boolean moreThanOne(ArrayList<Integer> list, int number) 
    {
      int count = 0;
      for (Integer in : list) {
          if (number == in) {
              count++;
          }
      }
      if(count > 1)
         return true;
      else 
         return false;
      }
    }

答案 2 :(得分:0)

你可以这样做:

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

    ArrayList<Integer> list = new ArrayList<>();
    list.add(3);
    list.add(2);
    list.add(7);
    list.add(2);

    Scanner scanner = new Scanner(System.in);

    System.out.print("Type a number: ");
    String input = scanner.nextLine();
    int number = Integer.parseInt(input);
    scanner.close();
    if(moreThanOnce(list, number)){
        System.out.println("The number appears more than once.");
    }else{
        System.out.println("The number doesn't appear more than once.");
    }

}

public static boolean moreThanOnce(ArrayList<Integer> list, int number) {
    boolean bool = false;
    int counter = 0;
    for (Integer value : list) {
        if (value == number) {
            counter++;
        }
    }
    if (counter > 1){
        bool = true;
    }
    return bool;
}
}

只是一个提示:你应该提高你的英语水平,这样你就可以更容易理解你的问题了。这样做的好方法是阅读用这种语言写的书。

答案 3 :(得分:0)

    System.out.println("Type a number: ");
    Set<Integer> set = new HashSet<Integer>(list);
    Scanner scanner = new Scanner(System.in);
    int number = Integer.parseInt(scanner.nextLine());

    if (!set.add(number)) {
        System.out.println(number + " appears more than once.");
    } else {
        System.out.println(number + " does not appear more than once.");
    }