如何计数名称java的数量
嗨,大家好。 我是Java的新手,目前正在学习字符串。
我有一个任务来计算名称的数量,名称的长度必须至少两个,名称的第一个字母应从上案例开始,第二个字母为较低的情况。
问题是我不知道如何使用字符。Isuppercase(text.charat(i))和targin.islowercase(text.Charat(i + 1))。
我会使用一些建议或提示。
class NameCounterTest {
public static void main(String[] args) {
// 1
System.out.println(new NameCounter().count("Mars is great planet"));
// 2
System.out.println(new NameCounter().count("Moon is near Earth"));
// 0
System.out.println(new NameCounter().count("SPACE IS GREAT"));
}
}
class NameCounter {
public int count(String text) {
String[] words = text.split(" ");
int wordLength = 0, counter = 0;
for (int i = 0; i < words.length; i++) {
String word = words[i];
wordLength = word.length();
if (wordLength >= 2 && Character.isUpperCase(text.charAt(i)))
counter++;
}
return counter;
}
}
Output:
1; //Should be 1;
1; //Should be 2;
3; //Should be 0;
Hi guys.
I'm new to Java, currently learning Strings.
I have a task to count the number of names, the length of the name must be at least two, the first letter of the name should start with upper case, the second with lower case.
The issue is that I don't know how to use the Character.isUpperCase(text.charAt(i)) and Character.isLowerCase(text.charAt(i + 1)) in the same if.
I would use some advice or hint.
class NameCounterTest {
public static void main(String[] args) {
// 1
System.out.println(new NameCounter().count("Mars is great planet"));
// 2
System.out.println(new NameCounter().count("Moon is near Earth"));
// 0
System.out.println(new NameCounter().count("SPACE IS GREAT"));
}
}
class NameCounter {
public int count(String text) {
String[] words = text.split(" ");
int wordLength = 0, counter = 0;
for (int i = 0; i < words.length; i++) {
String word = words[i];
wordLength = word.length();
if (wordLength >= 2 && Character.isUpperCase(text.charAt(i)))
counter++;
}
return counter;
}
}
Output:
1; //Should be 1;
1; //Should be 2;
3; //Should be 0;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
Word.Charat(0)
和Word.Charat(1)
以获取循环中每个单词中的第一个和第二个字符。You can use
word.charAt(0)
andword.charAt(1)
to get the first and second character in each word in the loop.