Java 如何调用返回单词数组(给定输入序列)的方法?
我被要求创建一个方法,在这个方法中,我输入一个字符串序列,并创建一个数组来存储字符串中的单词。到目前为止,我的情况如下:Java 如何调用返回单词数组(给定输入序列)的方法?,java,arrays,eclipse,string,methods,Java,Arrays,Eclipse,String,Methods,我被要求创建一个方法,在这个方法中,我输入一个字符串序列,并创建一个数组来存储字符串中的单词。到目前为止,我的情况如下: public class Tester{ public static String[] split(String s) { // determine the number of words java.util.Scanner t = new java.util.Scanner(s); int countWords = 0
public class Tester{
public static String[] split(String s) {
// determine the number of words
java.util.Scanner t = new java.util.Scanner(s);
int countWords = 0;
String w;
while (t.hasNext()) {
w = t.next();
countWords++;
}
// create appropriate array and store the string’s words in it
// code here
String[] words = new String[4]; // Since you are using an array you have to declare
// a fixed length.
// To avoid this, you can use an ArrayList
// (dynamic array) instead.
while (t.hasNext()) {
w = t.next();
words[countWords] = w;
countWords++;
}
return words;
}
}
现在我必须用字符串1234作为参数调用split方法。如果我听起来很天真,我道歉。我是编程新手。我已经看了很多关于这个的教程,但是当我尝试调用这个方法时,我的代码总是会出现红色标记
*代码的前14行(从“public class”到“code here”)是给我的问题的一部分,所以它们不应该被修改。如有必要,您可以更改代码的其余部分
编辑:
如何创建调用split方法的main方法?这就是我所尝试的:
class Demo
{
public static void main(String[]args)
{
Tester object = new Tester();
object.split(s);
System.out.println(words[i]);
}
}
基本上,我创建了另一个调用split方法的类。然而,我不断地得到红色标记。在第一次
while(t.hasNext())
循环之后,您的t
扫描仪已经用完了
您需要重新创建它,以便重新从头开始:
String[] words = new String[countWords]; // the size is countWords
t = new java.util.Scanner (s); // recreate the scanner
int index = 0;
while (t.hasNext()) {
words[index++] = t.next();
}
return words;
在评论中,有一个注释。由于您使用的是一个字符串数组,
String[]words
,因此您需要确定数组的长度,以便正确初始化、填充并使用它
第一次在扫描器中循环时,t
,将了解分配给您的字符串数
int countWords = 0;
while (t.hasNext()) {
w = t.next();
countWords++;
}
这意味着你至少还需要一个步骤来填满它。现在您已经知道了countWords
,以及给定的字数,可以初始化数组了
String[]words=新字符串[countWords]
您有一个countWords
-数字为空的String
对象数组。是时候加满了
我们现在将执行第二个循环,并填充单词
字符串数组
int i = 0;
while (t.hasNext()) {
words[i] = t.next();
i++;
}
就这样。现在把它还给打电话的人
返回单词
最后一项说明:
请仔细阅读如何正确缩进,正如我在你第一篇文章的评论中所说的。如果代码没有正确缩进,你真的无法写/读代码。首先,你根本不需要计算字数。相反,这可以简单地做到
ArrayList<String> wordsList = new ArrayList<String>(); This list will contain all your words
t = new java.util.Scanner (s);// scanner
while (t.hasNext()) {
wordsList.add(t.next());
}
return wordsList.toArray();
ArrayList wordsList=new ArrayList();此列表将包含您的所有单词
t=新的java.util.Scanner;//扫描仪
while(t.hasNext()){
添加(t.next());
}
返回单词list.toArray();
使用它的优点是,您不需要为数组或列表初始化任何大小 你的问题是?请仔细阅读