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/