gpt4 book ai didi

java - 从文本文件存储值到数组后,如何查找数组中的值?

转载 作者:行者123 更新时间:2023-11-30 01:46:28 25 4
gpt4 key购买 nike

我有一个代码将从文本文件中读取字符串并将其存储在字符串数组中。然后用户输入一个字符串并检查它是否存在于数组中。遗憾的是它总是打印错误

Name not found on my database :<.

我哪里出错了?

import java.util.Scanner;
import java.io.*;

class MaleNames{
static String names[] = new String[1362];
static Scanner readFile;
static String n;
static int i = 0;
static int x = 0;

public static void main(String args[]) throws Exception{
try {
readFile = new Scanner(new File("C:/Users/James Vausch/Desktop/MaleNames.txt"));
System.out.println("");
} catch (Exception e) {
System.out.println("Could not locate the data file! Please check the address of the file.");
}
readFile();
}

public static void readFile() throws Exception{
while(readFile.hasNext()) {
names[i] = readFile.next();
System.out.println((x + 1) + ". " + names[i]);
x++;
i++;
}
checkName();
}

public static void checkName() throws Exception{
System.out.println("Enter a name so that we can check that on my database. :3");
n = new Scanner(System.in).nextLine();
for(int j = 0; j < 1362; j++){
if(n.equalsIgnoreCase(names[j])){
System.out.println("Name found on my database :>");
break;
}else{
System.out.println("Name not found on my database. :<");
System.out.println(names[1000]);
break;
}
}

System.out.println("Do you want to search for another name? Yes or No?");
String ask = new Scanner(System.in).next();
if(ask.equalsIgnoreCase("Yes")){
checkName();
}else{
closeFile();
}
}

public static void closeFile() {
readFile.close();
}
}

这里我还有要保存在文本文件(MaleNames.txt)中的示例名称:

Joshua
James
Theodore
Thewa
Adrian

它应该在数组中找到字符串并打印

Name found on my database

最佳答案

问题出在这里:

for(int j = 0; j < 1362; j++){
if(n.equalsIgnoreCase(names[j])){
System.out.println("Name found on my database :>");
break;
}else{
System.out.println("Name not found on my database. :<");
System.out.println(names[1000]);
break;
}
}

此代码将在匹配的第一个名称处跳出循环,该名称始终是第一个名称(除非您碰巧在列表中输入了第一个名称)。

相反,您可以检查所有名称,并且仅在匹配目标名称时才中断,或者通过这样做而不是这样做来节省大量的痛苦和代码你的循环:

if (Arrays.asList(names).contains(n)) {
System.out.println("Name found on my database :>");
} else {
System.out.println("Name not found on my database. :<");
}

更好的是,使用Set<String>而不是String[]保存你的名字,在这种情况下测试就变成:

if (names.contains(n))

作为一般规则,优先使用集合而不是数组。

<小时/>

如果这是一个指定不使用集合(和流)的分配,则您必须执行以下操作:

boolean found = false;
for (int j = 0; j < names.length && !found; j++){
found = n.equalsIgnoreCase(names[j]);
}

if (found) {
System.out.println("Name found on my database :>");
} else {
System.out.println("Name not found on my database. :<");
System.out.println(names[1000]);
}

关于java - 从文本文件存储值到数组后,如何查找数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com