我必须能够输入任意两个单词作为字符串
The zero, one, infinity design rule 说没有两个这样的东西。让我们设计它来处理任意数量的单词。
String words = "One two many lots"; // This will be our input
然后调用并显示方法返回的第一个单词,
所以我们需要一个接受一个字符串并返回一个字符串的方法。
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static 让我们从 main 调用它,而无需创建任何实例。 public 可以让我们根据需要从另一个类调用它。
.split(" ") 创建一个以每个空格分隔的字符串数组。
[0] 索引该数组并给出第一个单词,因为 java 中的数组是零索引的(它们从 0 开始计数)。
并且方法必须是for循环方法
啊,废话,那么我们必须努力做到这一点。
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
我有点知道如何使用子字符串,并且我知道如何通过使用 .substring(0,x) x 作为第一个单词的长度来返回第一个单词。
就是这样,使用你提到的那些方法和 for 循环。你还想要什么?
但是我怎样才能让它不管我用什么短语来表示字符串,它总是返回第一个单词呢?
伙计,你很挑剔:) 好吧:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
把它们放在一起看起来像这样:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
它会打印这个:
One
嘿等等,你改变了那里的 firstWord 方法。
是的,我做到了。这种风格避免了对结果字符串的需要。从未习惯于垃圾收集语言或使用finally 的老程序员不赞成多次返回。他们想要一个地方来清理他们的资源,但这是 java,所以我们不在乎。你应该使用哪种风格取决于你的导师。
请解释一下你是做什么的,因为这是我在 CS 课上的第一年。谢谢!
我该怎么办?我发帖真棒! :)
希望对你有帮助。