我有一个代码,它带有nextLine()
函数的字符串参数并传递
某些函数返回最长的单词。
我想知道是否可以使用ArrayList
然后访问每个
带索引的字母表,以便我可以告诉字符串中有多少个单词
然后比较它们以便我可以返回最长的单词。
这是我的方式 开始。它适用于典型的阵列,但典型的阵列需要预定义的大小。
package senay;
import java.util.*;
public class Test {
static String LongestWord(String sen) {
ArrayList test = new ArrayList();
test.add(sen);
System.out.println(test.substring(0,1));
\\ it doesn't recongnize substring
return sen;
}
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
ArrayList testarray= new ArrayList();
System.out.println(testarray.add("enter sentence"));
System.out.println(LongestWord(s.nextLine()));
}
答案 0 :(得分:1)
正如Berger在his comment和Murat K.在his comment中所提到的,您的test
对象是ArrayList的一个实例。但ArrayList没有一个名为subString()
的方法,这就是为什么它告诉你它不被识别的原因。
subString()
是String的一种方法。因此,在调用subString之前,首先需要获取String。您正在操作的字符串为sen
,因此您可以拨打sen.subString()
。或者,如果要在存储在ArrayList中的另一个String上调用它,请使用方法get(index)
获取所需的String并在其上调用Substring:test.get(index).subString()
为了提示您的代码,ArrayList是一个类型化对象,它意味着您可以定义它将包含的对象类型。所以你应该(建议)定义你的ArrayList将包含String。 ArrayList<String> test = new ArrayList<String>();
答案 1 :(得分:0)
你要这样写:
System.out.println(((String)test.get(0)).substring(0,1));
在LongestWord
方法内。因为test.get(0)
将返回arraylist中的第一个对象,在调用它的substring方法之前需要将其强制转换为String。
答案 2 :(得分:0)
<强> Array
强>
// Split all words from input sentence
String[] array = string.split("\\s+");
// count the number of words
int total = array.length;
您可以获得最长的String
here
<强> ArrayList
强>
// Split all words from input sentence
List<String> list = new ArrayList<>(Arrays.asList(string.split("\\s+")));
// count the number of words
int total = list.size();
您可以获得最长的String
here