Java – how do I traverse an array and check for duplicates?
•
Java
I'm creating a program that allows you to store 10 items in an array What I can't let the program do is that if one of the input items already exists in the array, an error will occur
So, for example, if the array looks like [banana, potato, 3,4, yes,......] and I enter banana again, it should say "the item has been stored" and ask me to re-enter the value My current code 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++;
Solution
You can use nested loops to iterate through the array to see if new input exists It is better to do this in a function In addition, when performing this operation, you need to ensure that you are not in the first element, otherwise 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++;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
