如何停止重复输入(Java)

时间:2018-07-03 17:18:40

标签: java arrays java.util.scanner

我有一个简单的代码,要求用户输入项目并将其存储到数组中。我想这样做,以便当最后一个条目与第一个条目相同时该程序停止运行。

例如,这将停止程序,因为Cookie既将数组中的第一项也用于最后一项。但在此示例中,在“ Sugar”之类的数组中包含重复项也是可以的:

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");
    }

   }
}

感谢您的帮助

6 个答案:

答案 0 :(得分:1)

您可以通过使用if-condition方法添加简单的equals()来做到这一点。您需要添加以下if-condition

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

尝试此代码:-

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");
    }

   }
}

输出:-

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

答案 1 :(得分:1)

如果您不知道用户将输入的项目数,那么此代码将很有帮助,

import java.util.*;
public class MyClass {
public static void main(String[] args) {
    ArrayList<String> al = new ArrayList<String>();
    Scanner sc = new Scanner(System.in);
    while(true)
    {
        System.out.print("Enter name:");
        String temp = sc.next();
        if(al.isEmpty() != true)
        {
            if(temp.equals(al.get(0)))
                break;
        }
            al.add(temp);
    }
     for(int i = 0;i<al.size();i++)
     {
         System.out.println(al.get(i));
     }
}
}

答案 2 :(得分:1)

更复杂的 OO程序示例:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Grocery {

    List<String> basket; // list of items in the basket

    //constructor of Grocery with number of items provided
    public Grocery(int numberOfItems) {
        basket = new ArrayList<>(numberOfItems); // initialize basket
    }


    /**
     * Add item to basket only if it is not similar to the first item
     * return true if succeeded otherwise return false if it's duplicate
     * @param item
     * @return
     */
    public boolean addItem(String item) {
        if(basket.size()==0) return basket.add(item);
        if(!basket.get(0).equals(item)) {
            return basket.add(item);
        }
        return false;
    }

    /**
     * Remove specific item in the basket
     * or all items by name if "all" is true
     * @param item
     */
    public void removeItem(String item, boolean all) {
        if(all) {
            for(String i : basket) {
                if(i.equals(item)) {
                    basket.remove(i);
                }
            }
        }else {
            basket.remove(item);
        }
    }

    // method to empty the basket
    public void emptyBasket() {
        basket.clear();
    }


    /**
     * Override toString() to provide your own
     * textual representation of the basket
     */
    @Override
    public String toString() {
        String s = "";
        for(int i=0; i<basket.size(); i++) {
            s += "Item #" + (i+1) + " : " + basket.get(i) + "\n";
        }

        return s;
    }

    // TEST
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

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

        System.out.print("Enter How Many Items: ");

        try {
            numOfItems = Integer.parseInt(scan.nextLine().trim());
        }catch(NumberFormatException e) {
            System.out.print("Number of items you entered is invalid!");
            System.exit(0);
        }


        Grocery grocery = new Grocery(numOfItems);

        for (int i = 0; i < numOfItems; i++) {
            System.out.print("Enter Item " + (i+1) + " : ");
            if(!grocery.addItem(scan.nextLine())) {
                System.out.println("First Item Duplicate Detected!");
                //break;
                System.exit(0);
            };
        }

        scan.close();

        System.out.println(grocery.toString());
    }

}

测试

Test

答案 3 :(得分:0)

简单地添加一个条件,如果当前元素与第一个元素匹配,则退出for循环。

String first=null; 
for (int i = 0; i < arrayOfNames.length; i++) {
        System.out.print("Enter Item " + (i+1) + " : ");
        arrayOfNames[i] = scan.nextLine();
        if (i==0){
            first=arrayOfNames[i];
        }else{
            if(first==arrayOfNames[i]){break;}
        }
    }

答案 4 :(得分:0)

对我来说听起来像您应该能够在此处执行if语句以找出array [0] = array [i]

if (i > 0 && (arrayOfNames[0] == arrayOfNames[i])) {
    // do something
}

答案 5 :(得分:0)

只需将您的for循环条件更改为:

for (int i = 0; i == 0 || arrayOfNames[i] != arrayOfNames[0]; i++)