gpt4 book ai didi

java - 通过读取文件创建java数组

转载 作者:太空宇宙 更新时间:2023-11-04 13:23:21 24 4
gpt4 key购买 nike

我刚刚开始学习 Java,我正在尝试从我创建的文本文件中读取名称。然后我希望我的程序询问用户名称,然后检查该名称是否在该列表中。但是,我在使用数组时遇到问题,因此首先我尝试仅读取名称,然后将它们存储在数组中。这是我到目前为止所做的事情。

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;


public class readnames
{
public static void main(String[] args) throws FileNotFoundException
{
File file=new File("names.txt");
Scanner my_input = new Scanner(file);
int i=0;

String[] names = new String[20] ;

while(my_input.hasNext() && !names.equals("-1"))
{
names[i]=my_input.nextLine();
i++;
}

my_input.close();
System.out.println(names[i]);
}
}

最佳答案

    public static void main(String[] args) throws FileNotFoundException {
File file = new File("names.txt");
Scanner my_input = new Scanner(file);

ArrayList<String> names = new ArrayList<>();

while (my_input.hasNext()) {
String t =my_input.nextLine();
if( !t.equals("-1"))
names.add(t);

}


System.out.println("Enter name");
String nameToCheck = my_input.nextLine();
if (names.contains(nameToCheck)) {
System.out.println("Found");
}
my_input.close();
}

我建议您使用ArrayList<>,因为文件可能包含超过20个名称

使用普通数组

public static void main(String[] args) throws FileNotFoundException {
File file = new File("names.txt");
Scanner my_input = new Scanner(file);

String[] names = new String[20];
int i = 0;
while (my_input.hasNext()) {
String t = my_input.nextLine();
if(!t.equals("-1"))
names[i++] = t;
}


System.out.println("Enter name");
String nameToCheck = my_input.nextLine();
for (String temp : names) {
if (temp.equals(nameToCheck)) {
System.out.println("FOund");
}
}
my_input.close();
}

关于java - 通过读取文件创建java数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32864790/

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