我正在尝试创建一个字符串数组程序来查找最后一个匹配项。例如,当询问长度为 3 的最后一个单词时,代码应将“was”定位在索引 7 处。这是我到目前为止所拥有的,但我不确定如何确保代码返回最后一个匹配的位置:
public static void main(String[] args)
{
String[] words = { "Mary", "had", "a", "little", "lamb",
"it's", "fleece", "was", "white", "as",
"snow" };
Scanner in = new Scanner(System.in);
System.out.print("Word length: ");
int wordLength = in.nextInt();
boolean found = false;
int pos = 0;
while (!found)
{
if (wordLength == words[pos].length())
{
pos++;
}
else
{
found = true;
}
}
if (pos > 0)
{
System.out.println("Found " + words[pos] + " at position " + pos);
}
else
{
System.out.println("No word of length " + wordLength);
}
}
最佳答案
public static void main(String[] args)
{
String[] words = { "Mary", "had", "a", "little", "lamb",
"it's", "fleece", "was", "white", "as",
"snow" };
Scanner in = new Scanner(System.in);
System.out.print("Word length: ");
int wordLength = in.nextInt();
boolean found = false;
int pos;
for(int i = words.length-1 ; i >= 0 ; i--)
{
if (wordLength == words[i].length())
{
pos =i;
found = true;
break;
}
}
if (found)
{
System.out.println("Found " + words[pos] + " at position " + pos);
}
else
{
System.out.println("No word of length " + wordLength);
}
}
关于java - 如何创建一个查找最后一个匹配项的字符串数组程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45182386/