gpt4 book ai didi

java - 如何创建一个查找最后一个匹配项的字符串数组程序?

转载 作者:太空宇宙 更新时间:2023-11-04 11:18:33 25 4
gpt4 key购买 nike

我正在尝试创建一个字符串数组程序来查找最后一个匹配项。例如,当询问长度为 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/

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