java - 扫描仪输入和数组重复验证导致无限循环
问题描述
我编写了一个列出输入名称的程序。但是如果输入的名字已经在数组中,用户必须重新输入一个不同的名字。
我在下面留下了一张图片,显示了我运行代码时发生的情况
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();
}
}
解决方案
你的问题是这一行:
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);
}
推荐阅读
- powershell - Azure DevOps 代理上的 PowerShell 存储库问题
- python - 如何更改 x 轴上的数字(matplotlib)
- session - Laravel 7:如何清除 withErrors 会话
- mysql - 我是否允许在 Sequelize 中定义用户和服务器模型之间的多对多和一对多关系?
- java - 无法使用 maven 将类从一个模块导入另一个模块
- c++ - 保存地图
到文本文件 - rsync - rsync 间歇性地失败,在同一命令上出现不同的错误代码
- pyspark - ParquetDecodingException 使用 pyspark
- bash - crontab 不执行脚本和日志文件不工作
- python - 使用 Python Elasticsearch Client 为空索引添加索引模式