gpt4 book ai didi

java - 如何查找以用户输入的字母开头的名称?

转载 作者:行者123 更新时间:2023-11-29 05:13:44 25 4
gpt4 key购买 nike

我创建了一个 ArrayList 来存储客户的姓名。然后我用一些名字填满了列表。

现在我想要求用户输入一个字母,然后查找所有以输入的字母开头的名字所有包含输入字母的名称。

这就是我到现在为止:

    package costomersearching;

import java.util.ArrayList;
import java.util.Scanner;

public class CostomerSearching {

public static void main(String[] args) {
ArrayList<String> customerName = new ArrayList();
Scanner input = new Scanner(System.in);
customerName.add("Sara");
customerName.add("John");
customerName.add("Miami");
customerName.add("Mart");
customerName.add("Alex");

System.out.println("Customer List: \n" + customerName);
System.out.println("Search Customer by letter: ");
String letter = input.next();
//show the name containg the letter starting as the first letter
//Show the name containing the letetr.
}

}

最佳答案

简单地遍历您的 ArrayList 并搜索正确的名称。你可以这样做:

//show names containing the letter starting as the first letter
for(String i : costumerName) {
if(i.startsWith(letter)) System.out.println(i);
}

//show names containing the letter
for(String i : costumerName) {
if(i.contains(letter)) System.out.println(i);
}

希望这有帮助:)

关于java - 如何查找以用户输入的字母开头的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27335716/

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