首页 > 解决方案 > 从文本文件中存储值后如何在数组中查找值?

问题描述

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

在我的数据库中找不到名称:<。

我哪里做错了?

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

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

在我的数据库中找到的名称

标签: java

解决方案


问题在这里:

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

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

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

推荐阅读