我必须能够输入任何两个单词作为字符串.调用获取该字符串并返回第一个单词的方法.最后显示那个词.
该方法必须是for循环方法.我知道如何使用substring,我知道如何通过使用.substring(0,x)x返回第一个单词x是第一个单词的长度.
我怎样才能这样做,无论我用什么短语用于字符串,它总会返回第一个字?请解释你的工作,因为这是我在CS课程的第一年.谢谢!
我必须能够输入任何两个单词作为字符串
零,一,无限设计规则说没有两个这样的东西.让我们设计它可以使用任意数量的单词.
String words = "One two many lots"; // This will be our input
Run Code Online (Sandbox Code Playgroud)
然后调用并显示从该方法返回的第一个单词,
所以我们需要一个接受String并返回String的方法.
// 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
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我知道如何使用substring,我知道如何通过使用.substring(0,x)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;
}
Run Code Online (Sandbox Code Playgroud)
把它们放在一起它看起来像这样:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
它打印出来:
One
Run Code Online (Sandbox Code Playgroud)
嘿等等,你改变了那里的firstWord方法.
是啊,我做了.此样式避免了对结果字符串的需要.从未习惯于垃圾收集语言或使用的旧程序员不赞成多次返回finally.他们想要一个地方来清理他们的资源,但这是java,所以我们不在乎.您应该使用哪种风格取决于您的教练.
请解释你的工作,因为这是我在CS课程的第一年.谢谢!
我该怎么办?我发帖太棒了!:)
希望能帮助到你.