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

标签 java arrays arraylist

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/

相关文章:

java - 输入字符串并在每次单击按钮时添加到列表中,同时显示输入的所有字符串

arrays - 如何在 Go 中将错误数组转换为 JSON

c# - 从数组转换为十进制

java - 通过搜索Firebase获取特定的节点

java - 实现从数据库到表单的下一个和上一个

java - 数组中的数组; Java(帮助完成实验作业)

java - 将逗号分隔的字符串转换为尾随逗号分隔的数组列表

java - 向 Map 添加值时类型不兼容

Java Swing 窗口太高

java - 检测具有已知 ID 的隐藏蓝牙设备