gpt4 book ai didi

java - 数组中包含开头和结尾元音的最长字符串

转载 作者:行者123 更新时间:2023-11-30 03:15:38 25 4
gpt4 key购买 nike

我试图获取数组中以元音开头和结尾的最长字符串。当我运行代码时,每次循环后都会显示最长的值,但不会显示变量longest的最高值。

class xJava
{
public static void firstlastVowel (String theString)
{
int index;
int longest=0;
char x = theString.charAt(index=0);
char y = theString.charAt(theString.length()-1);
int z = theString.length()-1;

if(x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u')
{
if(y == 'a' || y == 'e' || y == 'i' || y == 'o' || y == 'u')
{
System.out.println(theString + " starts and ends with a vowel");

if(z > longest)
{
longest = z;
System.out.println("longest string is "+longest+" characters!");
}
}


}
}



public static void main (String[] args)
{
int index;
String value;

String[] things = {"abba", "orlando", "academia", "ape"};


for(String thing : things)
{
firstlastVowel(thing);
}

}

}

如何让变量longest仅包含最长字符串的长度?

输出是:

 abba starts and ends with a vowel
longest string is 3 characters!
orlando starts and ends with a vowel
longest string is 6 characters!
academia starts and ends with a vowel
longest string is 7 characters!
ape starts and ends with a vowel
longest string is 2 characters!

最佳答案

啊,我应该知道不应该发布这个:

  String[] things = { "aa", "orrro", "academia", "ape" };
int longest = Arrays.stream(things)
.filter(s -> s.matches("^[aeiouy].*[aeiouy]$"))
.map(String::length)
.reduce(0, Math::max);
System.out.println("longest string is " + longest + " characters!");

为什么以及如何运作留给读者作为练习。

关于java - 数组中包含开头和结尾元音的最长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32727072/

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