java - 从文本文件中存储值后如何在数组中查找值?
问题描述
我有一个代码,它将从文本文件中读取字符串并将其存储在字符串数组中。然后用户将输入一个字符串并检查它是否存在于数组中。可悲的是它总是打印一个错误
在我的数据库中找不到名称:<。
我哪里做错了?
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
它应该在它的数组中找到字符串并打印
在我的数据库中找到的名称
解决方案
问题在这里:
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]);
}
推荐阅读
- android - Android中的线程池,直接调用doinbackground
- javascript - 正方形内的多种颜色变化(填充)(P5.js)
- php - 创建“选择”以选择和显示所选国家/地区的问题
- python-3.x - ValueError:从 S3 存储桶加载 pkl 文件时出现“嵌入的空字节”
- tensorflow - “keras.backend.variable”在 keras 中的行为与 tensorflow 不同
- ruby - 为什么 Linux 上的 Ruby 对 File.writable 返回 true?('/tmp/file') 但在尝试写入文件时会引发 Errno::EACCES?
- javascript - PaperJS trouble creating circle on mouseDown
- php - MySQLi 面向对象的重定向取决于用户角色
- excel - 我的一些数据表列在 excel 中显示为数字数据类型如何防止将其定义为没有逗号分隔符的数字
- c - 如何在 For 循环中使用多个字符数组和浮点数组?