Java 猜猜你在想谁的计划(理论)
在Java中,我创建了一个程序,要求用户想到他们认识的人 然后,我的程序要求他们输入名字的第一个字母,以及姓氏的最后一个字母,不带空格 我想让我的程序查看一个全名数组,找到第一个字母与用户输入的第一个字母匹配的那个,以及他们姓氏的对应最后一个字母 以下是我目前的计划:Java 猜猜你在想谁的计划(理论),java,arrays,Java,Arrays,在Java中,我创建了一个程序,要求用户想到他们认识的人 然后,我的程序要求他们输入名字的第一个字母,以及姓氏的最后一个字母,不带空格 我想让我的程序查看一个全名数组,找到第一个字母与用户输入的第一个字母匹配的那个,以及他们姓氏的对应最后一个字母 以下是我目前的计划: import java.util.* ; public class Guesser { public static void main(String[] args) { Scanner UserIn
import java.util.* ;
public class Guesser
{
public static void main(String[] args)
{
Scanner UserInput = new Scanner(System.in);
String [] names = {"firstname lastname " + "etc"}; //example name array
System.out.print( "Hello! I am a robot. I might be smart, but I don't know. Please play a game with me to help me see if I am smart." + "\n" + "What I want you to do is think of someone you know." + "\n" + "Enter the first letter of their first name, and the last letter of their last name. Please no spaces. Then, press enter. " );
String TheirGuess = UserInput.nextLine(); //get their input, assign a string to it
System.out.println("You entered: " + TheirGuess);
char FirstChar = TheirGuess.charAt(0); // get the the first char
char SecondChar = TheirGuess.charAt(1); // get the second char
System.out.println("I will now think of someone whose first name starts with " + FirstChar + " and last name ends with " + SecondChar );
UserInput.close();
}
}
如何在字符串数组中搜索第一个字符为FirstChar,最后一个字符为SecondChar的名称 有一段时间没有用Java编写,但应该是这样的:
String names[] = new String[] { "AAA BBB", "CCC DDD", "EEE FFF" };
Scanner input = new Scanner(System.in);
String userInput = input.nextLine().toLowerCase();
String result = "None";
for (String name : names) {
String[] nameSplitted = name.toLowerCase().split(" ");
if (nameSplitted[0].charAt(0) == userInput.charAt(0) &&
nameSplitted[1].charAt(0) == userInput.charAt(1)
) {
result = name;
break;
}
}
System.out.println("Result is: " + result);
执行此操作的有效方法是使用两个TreeSet对象。一个包含姓名,另一个包含姓氏。然后您可以使用subSet方法来获取条目。例如:
TreeSet<String> names = new TreeSet<>();
names.add("Antonio");
names.add("Bernard");
names.add("Peter");
names.add("Zack");
Set<String> bNames = names.subSet("B", "C");
请注意,此实现区分大小写。但是只要稍作调整,您就可以修复它-我将把这个问题留给您。这可以在一行代码中完成
// Assuming you have populated a Set (actually any Collection) of names
Set<String> names;
List<String> matchedNames = names.stream()
.filter(s -> s.matches(userInput.replaceAll("^.", "$0.*")))
.collect(Collectors.toList());
此代码识别您可以有多个匹配项
虽然这看起来像是填鸭式的,但这个答案的价值在于找出它是如何工作的。我知道这个程序中还没有数组。从用户处读取数据作为字符串,并使用charAt或substring。
names.stream()
.filter(s -> s.matches(userInput.replaceAll("^.", "$0.*")))
.forEach(System.out::println);