简体   繁体   中英

Only one Occurrence in Java

    Scanner in = new Scanner(System.in);
    x = new Scanner(new File("C:\\me.txt"));
    int count = 0;
    ArrayList<String> b = new ArrayList<>();

    while((x.hasNext()))
    {
        String a = x.next();
                int num = 0;
                for(int i=0;i<count;i++)
                {
                    if((b.get(i).equals(a)))
                    {num++;}
                }
        if(num==1)
        {b.add(a);}
        count++;
    }

I want to add the element to b only when the occurence is only one. But there seems some error i keep getting.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

Or does b.get(i) equal to NULL in first iteration?

    if((b.get(i).equals(a)))

You got this error because b is empty it doesn't contain any element ,and you are trying to access element in it b.get(i) so you got java.lang.IndexOutOfBoundsException , use contains to find if the list have that element and if not add it to the list or use Set it doesn't allow duplicates

 int count = 0;
 ArrayList<String> b = new ArrayList<>();
 while((x.hasNext()))
    {
        String a = x.next();
        if(!b.contains(a)){
           b.add(a);
        }
        count++;
    }

Please

  • check the line

     if ((b.get(i).equals(a))); 

    It contains a semi-colon at the end and I think this is wrong: The next statement in curly braces ( num++; ) is executed every time and not only if the condition matches.

  • check if b.get(i) is null before calling equals on it. You know already that a is not null , hence it would make more sense to check for a.equals(b.get(i))

  • check the usage of count . Its value is not related to the size of the array list, but you use it this way in the loop.In your implementation a situation can arise in which the value of count is greater than the size of the list. This results in an IndexOutOfBoundsException .

Apparently you're trying to use count as the length of b . However, count is incremented more often than b is added to.

Possible solutions are:

  • Either update count only when you add something to b
  • or scratch count altogether and use b.size() in the for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM