3

I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.

So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:

public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int stringNumber = 0;
        String[] stringArray = new String[10];

        for (int i = 0; i <= stringArray.length; i++) {

            out.println("\nEnter a string");
            String input = keyboard.next();
            stringArray[stringNumber] = input;
            out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");

            PrintArray(stringArray);
            stringNumber++;
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Gregg1989
  • 675
  • 6
  • 14
  • 24
  • 1
    I don't understand the question. WHat exactly prevents you from going through the array and checking for duplicates? – Ingo Oct 24 '13 at 11:51
  • 1
    there is missing some code – Philipp Sander Oct 24 '13 at 11:51
  • add them to a set, if it already exists, it wont allow you to do so. convert to an array at the end (should you really need an array specifically?) – Chris Oct 24 '13 at 11:52
  • don't write your own `printArray`-method. use `System.out.println(Arrays.toString(stringArray));` – Philipp Sander Oct 24 '13 at 11:53
  • lngo, the problem is that I don't know how to loop through the array and see if the input string value already exists. (I'm a beginner) – Gregg1989 Oct 24 '13 at 11:54
  • if the size of array is extending and going be huge, so may need some [thread(s)](http://arashmd.blogspot.com/2013/06/java-threading.html) to check the duplication of the word. –  Oct 24 '13 at 11:55
  • @user2915567 you know how to loop through an array (your code just does this already), hence I assume you don't know how to compare two items? How to remember the result of multiple comparisions? Or something else? – Ingo Oct 24 '13 at 11:58
  • I don't know how to compare every single item in the array to every other item in the array and determine whether the value == any of the other items. – Gregg1989 Oct 24 '13 at 12:04

7 Answers7

3

It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.


If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.

public static boolean contains(String[] array, String value) {
    // Iterate over the array using for loop
    // For each string, check if it equals to value.
    // Return true, if it is equal, else continue iteration
    // After the iteration ends, directly return false.
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.

for (int i = 0; i <= stringArray.length; i++) {

        boolean isInArray = false;

        System.out.println("\nEnter a string");
        String input = keyboard.next();

        if (i > 0) {

            for (int j = 0; j < stringArray.length; j++) {
                if (stringArray[j].equalsIgnoreCase(input)) {
                    isInArray = true;
                    break;
                }
            }
        }
        if (!isInArray) {
            stringArray[stringNumber] = input;
        } else {
            System.out.println("\"" + stringArray[stringNumber-1] + "\""
                    + " has been stored.");
        }
        PrintArray(stringArray);
        stringNumber++;
    }
Matt Penna
  • 117
  • 7
  • I only used loops and arrays assuming this is for a school assignment and you could not use other data types. – Matt Penna Oct 24 '13 at 12:03
  • There's a small bug in this code, but I'm working on fixing it! Thanks Matt, this gave me a much better perspective on the direction I should be taking with this program. :) – Gregg1989 Oct 24 '13 at 12:26
1

When you got the String input, you can create a method that will :

  1. Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
  2. Returns a boolean value wheter the string is in the array or not
  3. Then just add a while structure to re-ask for an input

Basically it can look like this :

String input = "";    
do {
    input = keyboard.next();
}while(!checkString(input))

The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.


Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • That's exactly what I thought I should do. The thing is that I've been using Java for 2 days and I'm not sure how to write that piece of code :( – Gregg1989 Oct 24 '13 at 11:52
0

You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.

public boolean exists(String[] strs, String search){
    for(String str : strs){
        if(str.equals(search))
           return true;
    }
    return false;
}

performance would be O(n) as it searchs linearly.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
0

Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.

For me the best solution is to have a helper HashSet to check the item for presence.

Also have a look at this question.

Community
  • 1
  • 1
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

To avoid you should use an Set instead of an array and loop until size = 10.

If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.

Olivier.Roger
  • 4,241
  • 5
  • 40
  • 68
0
while (no input or duplicated){
     ask for a new string
     if (not duplicated) {
          store the string in the array
          break;
     }
}
Evans
  • 1,589
  • 1
  • 14
  • 25