如何从文本文件中搜索名称

时间:2018-07-30 04:03:09

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

如何使扫描仪发现名称不区分大小写?例如,如果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

            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

  1. if (search.contains("Emily")) {}
  2. if (search.indexOf("Emily") > -1) {}

答案 1 :(得分:1)

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...    
            }
        }
    }
}