【问题标题】:How to search for a name from a text file如何从文本文件中搜索名称
【发布时间】:2019-01-06 06:47:00
【问题描述】:

如何让扫描仪发现名称不区分大小写?例如,如果 Emily 在文本文件中。

import java.util.*;
import java.io.*;

public class BabyNames {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner console = new Scanner(System.in);
        System.out.println("** Popularity of a baby name since year 1920 **");
        System.out.print("name? ");
        String name = console.next();

        Scanner input = new Scanner(new File("names.txt"));
        while (input.hasNext()) {
            String search = input.next();
            if (search = name) { // need help here

            }
        }
    }
}

【问题讨论】:

    标签: java loops if-statement java.util.scanner


    【解决方案1】:
    1. if (search.contains("Emily")) {}
    2. if (search.indexOf("Emily") > -1) {}

    【讨论】:

      【解决方案2】:

      String 类有一个您可能想要使用的 equalsIgnoreCase()

      import java.util.*;
      import java.io.*;
      
      public class BabyNames {
      
          public static void main(String[] args) throws FileNotFoundException {
              Scanner console = new Scanner(System.in);
              System.out.println("** Popularity of a baby name since year 1920 **");
              System.out.print("name? ");
              String name = console.next();
      
              Scanner input = new Scanner(new File("names.txt"));
              while (input.hasNext()) {
                  String search = input.next();
                  if (search.equalsIgnoreCase(name)) { 
                      // Do something...    
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-25
        • 1970-01-01
        • 2012-08-02
        • 1970-01-01
        • 2021-12-02
        • 2015-09-11
        • 1970-01-01
        相关资源
        最近更新 更多