在网上搜索到目前为止,我只能得到第一个大写字。 “神奇女侠”和“复仇者联盟”只获得第一个单词而非第二个单词中的第一个字母。 我基本上都在寻找那种“java技巧”来做这个技巧,而不是使用像WordUtilize这样的不同类或者它是什么。
这是我的代码:
public class Movie extends Shows{
private static String title;
private static HashSet<String> _Movie;
private static float time;
public static void main(String[] args) {
getTitle();
}
public static void getTitle() {
theMovies();
Scanner _title = new Scanner(System.in);
System.out.println("Which movie would you like to see?");
title = _title.nextLine();
title = title.substring(0,1).toUpperCase() + title.substring(1).toLowerCase();
_title.close();
System.out.println("You entered " + title + " movie");
if(_Movie.contains(title)) {
System.out.println(title);
} else {
System.out.println("Sorry, we only have Batman, Superman, Wonder Woman, and The Avengers");
}
}
public static void theMovies() {
_Movie = new HashSet<>();
_Movie.add("Batman");
_Movie.add("Superman");
_Movie.add("Wonder Woman");
_Movie.add("The Avengers");
}
}
这是我得到的结果:
你想看哪部电影? 神奇女侠 你进入了神奇女子电影 对不起,我们只有蝙蝠侠,超人,神奇女侠和复仇者
感谢阅读! 编辑对不起图片。不知道这是一个大问题。 :/
答案 0 :(得分:1)
如果您将代码发布为文本而不是图像,那将会很有帮助,但我的建议是:
继承java代码:
// split into words
String[] words = title.split(" ");
// capitalize each word
for (int i = 0; i < words.length; i++)
{
words[i] = words[i].substring(0, 1).toUpperCase() + words[i].substring(1).toLowerCase();
}
// rejoin back into a sentence
title = String.join(" ", words);
答案 1 :(得分:1)
假设空格为分隔符,您可以使用StringBuffer
将单词的第一个字母转换为大写。
public String toFirstCharUpperAll(String string){
StringBuffer sb=new StringBuffer(string);
for(int i=0;i<sb.length();i++)
if(i==0 || sb.charAt(i-1)==' ')//first letter to uppercase by default
sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
return sb.toString();
}