gpt4 book ai didi

java - 在 Java ArrayList 中搜索逗号分隔值 - 字符串和 int 组合。

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:57 26 4
gpt4 key购买 nike

首先,感谢您所做的一切。我是 Java 新手,我正在创建一个程序来询问用户姓名、票据类型和罚款金额。我正在获取该信息并将其写入文本文件(project.txt)。我正在使用 Scanner readArray 读取 txt 文件的内容,然后将内容排序到“列表”数组中。我已按字母顺序对列表进行排序,现在我想在数组中搜索从用户输入输入的关键字。该列表存储为“名称,票证类型,罚款(例如:迈克,超速,250.00”。当用户输入要搜索的名称(例如:迈克)时,我找不到...即使迈克,速度,100.00在project.txt中。我觉得它与逗号分隔值有关,但是,我必须以这种方式格式化它。代码如下(请友善!我会在代码工作后清理代码...)

import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
import java.text.Collator;
public class Project {

public static void main(String[] args) throws IOException {

String name = "";
String ticketType = "";
double fine;
char quit;
boolean cont = true;

while (cont){
do {
PrintStream out = new PrintStream(new FileOutputStream("Project.txt", true));
Scanner input = new Scanner(System.in);

System.out.println("Name:");
name = input.nextLine();
System.out.println("Ticket Type:");
ticketType = input.nextLine();
System.out.println("fine:");
fine = input.nextDouble();
System.out.println("press 'q' if you are done entering or 'c' to continue entering");
quit = input.next().toLowerCase().charAt(0);
out.print(name + ", ");
out.print(ticketType + ", ");
out.printf("%.2f",fine);
out.println();
out.close();
}
while (!(quit == 'q'));{
System.out.println("done");
}
Scanner input = new Scanner(System.in);
System.out.println("are you sure youre done");
System.out.println("enter y to if your done, n to enter more");
char Continue = input.next().toLowerCase().charAt(0);

if (Continue == ('y')){
cont = false;
}
//Done entering names to list
//Now read in file to array and sort alphabetically

}
Scanner readArray = new Scanner(new File("Project.txt"));
ArrayList<String> list = new ArrayList<String>();
while (readArray.hasNext()){
list.add(readArray.next().toLowerCase());

}
readArray.close();
Collections.sort(list, Collator.getInstance()); //sort array alphabetically
list.forEach(System.out::println); //print array as list ',' separated
Scanner search = new Scanner(System.in);
System.out.println("search keyword: ");
String keyword = search.next().toLowerCase();
System.out.println("searching for: " + keyword);
if (list.contains(keyword)){
System.out.println("found");
}
else {
System.out.println(" not found");
}
}
}

最佳答案

正如 Arkadiy 正确提到的,该列表不包含“mike”,而是“mike,超速,250.00”。

一个可能的简单搜索实现是:

  String keyword = search.next().toLowerCase();
System.out.println("searching for: " + keyword);

boolean found = false;
for (String element : list) {
if (element.contains(keyword)) {
found = true;
}
}

if (found) {
System.out.println("found");
}
else {
System.out.println(" not found");
}
}

关于java - 在 Java ArrayList 中搜索逗号分隔值 - 字符串和 int 组合。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42985127/

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