如何打印出一个词了Java中的用户输入的?例如:用户输入:“我们爱你的妈妈,她是最好的”。假设打印“妈妈”,因为第一个和最后字符的程序是相同的。我的代码不会打印在最后什么。这里是我的代码:
Scanner s = new Scanner(System.in);
System.out.println("Please enter a Sentence");
String input=s.nextLine();
String builderString=" ";
for(int i=0,j=0;i<input.length();i++){
if(input.charAt(i)==' '){
j=i+1; //upper the value of J if there is space (J will always check first char)
if (input.charAt(j)==input.charAt(i)&&j<i) {//an if statement to check for match chars.
builderString=" "+input.charAt(i);// insert the char into a new string to print it in the console.
}
}
}
}
System.out.println(builderString);
}
}
而不是解析字符串的每一个字母,你可以在你输入分成单词数组和单独检查每个字。
你可以把你的循环,但是你只需要检查chart at 0
是不是同时在一word.length() - 1
这里是一个工作的例子。请注意,我已经删除扫描部分,使之在我使用的游乐场工作。
// This would be de equivalent of your scanner
String input = "We love mom she is the best";
String[] words = input.split(" ");
String output = "";
for(int i=0;i<words.length; i++){
String currentWord = words[i];
if(currentWord.charAt(0) == currentWord.charAt(currentWord.length() -1)) {
output = currentWord;
}
}
System.out.println(output);
你也不需要你j
变没了。
你可以测试一下这里
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句