首页 > 解决方案 > 扫描仪输入和数组重复验证导致无限循环

问题描述

我编写了一个列出输入名称的程序。但是如果输入的名字已经在数组中,用户必须重新输入一个不同的名字。

我在下面留下了一张图片,显示了我运行代码时发生的情况

import java.util.Scanner;

public class list {
    public static void main(String[] args) {
        int numberofhumans;
        Scanner al = new Scanner(System.in);
        System.out.print("Enter the number of person: ");
        numberofhumans = al.nextInt();

        String[] list = new String[numberofhumans];
        for (int i = 0; i < numberofhumans; i++) {
            System.out.print("Enter the name:");
            list[i] = al.nextLine();

            for (int j = 0; j < i; j++) {
                if (list[i] == list[j]) {
                    System.out.println("Name you just typed is already in your list. Enter a different name.");
                    i--;
                }
            }

        }

        for (String string : list) {
            System.out.println(string);
        }
        al.close();
    }
}

1

标签: javaarraysduplicates

解决方案


你的问题是这一行:

if (list[i] == list[j])

这将检查 2 个对象是否相等,即使它们的内容相同,它们也不相等。您需要使用 String 对象的 .equals 方法来比较 2 个字符串。那应该可以解决问题:

if (list[i].equals(list[j]))

我宁愿使用一组字符串而不是数组来获得更好的性能,因为您不必为每个新输入一遍又一遍地迭代。就像是:

    Set<String> set = new HashSet<>();
    for (int i = 0; i < numberofhumans; i++) {
        System.out.print("Enter the name: ");
        String name = al.nextLine();
        while (set.contains(name)) {
           System.out.println("Name you just typed is already in your list. Enter a different name.");
           System.out.print("Enter the name: ");
           name = al.nextLine();
        }
        set.add(name);
     }

推荐阅读