gpt4 book ai didi

java - 读取数组列表以查找特定字符串和值的方法

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

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

BufferedReader reader = new BufferedReader(new FileReader("fruit.txt"));

System.out.println("enter the fruit you want to search");
Scanner input = new Scanner(System.in);
String fruit = input.nextLine();
String line;

List<String> list = new ArrayList<String>();
while((line=reader.readLine()) !=null)
{
list.add(line);
}

reader.close();

for (String s : list) {
System.out.println(s);
}
}
}

我有水果.txt

apple 20 good
orange 30 good
banana 40 needmore

如何从数组列表中检索我有多少橙子。我希望程序在这种情况下读取用户输入“橙色”并显示 30 并且状态不好。

理想的输出是

You have orange 30 of them and status is good

最佳答案

试试下面更新的类。

public class array
{

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

BufferedReader reader = new BufferedReader(new FileReader("fruit.txt"));

System.out.println("enter the fruit you want to search");
Scanner input = new Scanner(System.in);
String fruit = input.nextLine();

String line;

boolean found = false;
int count = 0;

List<String> list = new ArrayList<String>();
while ((line = reader.readLine()) != null)
{
String[] items = line.split(" ");

if (fruit.equals(items[0]))
{
found = true;
count = Integer.parseInt(items[1]);
break;
}

list.add(line);
}

reader.close();

if (found)
{
System.out.println("You have " + fruit + " " + count + " of them and status is good");
}
}
}

关于java - 读取数组列表以查找特定字符串和值的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13070245/

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