首页 > 解决方案 > How to stop on duplicate entry (Java)

问题描述

I have a simple code that asks a user to input items and stores them into an array. I would like to make it so the program stops running when the last entry is the same as the first.

so for example this would stop the program because Cookie it both the first item in the array and the last. But it's also ok to have duplicates with in the array like "Sugar" in this example:

Enter the item: Cookie
Enter the item: Sugar
Enter the item: Milk
Enter the item: Sugar
Enter the item: Salt
Enter the item: Cookie  

Main.java

import java.util.Scanner;

public class Main {


public static void main(String[] args){
    Scanner scan = new Scanner(System.in);

    //Decide the number of items
    int numOfItems = 20;

    //Create a string array to store the names of your items
    String arrayOfNames[] = new String[numOfItems];
    for (int i = 0; i < arrayOfNames.length; i++) {
        System.out.print("Enter Item " + (i+1) + " : ");
        arrayOfNames[i] = scan.nextLine();
    }

    //Now show your items's name one by one
    for (int i = 0; i < arrayOfNames.length; i++) {
        System.out.print("Item # " + (i+1) + " : ");
        System.out.print(arrayOfNames[i] + "\n");
    }

   }
}

Thanks for your help

标签: javaarraysjava.util.scanner

解决方案


You can do this by adding a simple if-condition with equals() method. you need do add following if-condition.

if(Temp.equals(arrayOfNames[0])) // readed Temp equals to first element.

Try this code:-

import java.util.Scanner;

public class Main {


public static void main(String[] args){
    Scanner scan = new Scanner(System.in);

    //Decide the number of items
    int numOfItems = 20,maxItems=0; // total items may vary

    //Create a string array to store the names of your items
    String arrayOfNames[] = new String[numOfItems];
    String Temp="";                              // for temporary storage
    for (int i = 0; i < arrayOfNames.length; i++) {
        System.out.print("Enter Item " + (i+1) + " : ");

        Temp= scan.nextLine();
        if(Temp.equals(arrayOfNames[0])){      
            maxItems=i;
            break;
        }
        else{
            arrayOfNames[i]=Temp;
        }
    }

    //Now show your items's name one by one
    for (int i = 0; i < maxItems; i++) {
        System.out.print("Item # " + (i+1) + " : ");
        System.out.print(arrayOfNames[i] + "\n");
    }

   }
}

Output :-

Enter Item 1 : Cookie
Enter Item 2 : Sugar
Enter Item 3 : milk
Enter Item 4 : Sugar
Enter Item 5 : Salt
Enter Item 6 : Cookie
Item # 1 : Cookie
Item # 2 : Sugar
Item # 3 : milk
Item # 4 : Sugar
Item # 5 : Salt

推荐阅读