创建一个包含以下静态方法的StringDemo类: •一种接受句子的方法,使用单个空格对其进行标记,然后仅打印以“pre”开头的单词。 •声明2个变量并将其初始化为您选择的句子的主要方法;然后使用2个句子测试您在上一步中定义的方法。
我的尝试
import java.util.ArrayList;
public class StringDemo{
public static void main(String... args){
String S1 = "We love prefix that have car strongly wheels and car
seats";
String S2 = "I have a lovely designed car that has many car features
beautifully and the car has a good car";
printWordsWithPre(S1);
printWordsWithPre(S2);
System.out.println(printWordsWithPre(S1));
System.out.println(printWordsWithPre(S1));
}
//- Tokenises a string/sentence and prints only the words that end with
ly.
public static void printWordsWithPre(String str){
String[] sTokens = str.split("\\p{javaWhitespace}");
for(int i = 0; i < sTokens.length; i++){
if(sTokens[i].endsWith("pre")){
System.out.println(sTokens[i]);
}
}
}
答案 0 :(得分:2)
您使用{{1}}代替{{1}}
答案 1 :(得分:2)
请尝试以下代码:
import java.util.ArrayList;
public class StringDemo{
public static void main(String... args){
String S1 = "We love prefix that have car strongly wheels and car seats";
String S2 = "I have a lovely designed car that has many beautifully predesigned car features and the car has a good prebuilt car";
printWordsWithPre(S1);
printWordsWithPre(S2);
// These functions don't return any data so they can't be printed. The results are already printed in the function above.
/*System.out.println(printWordsWithPre(S1));
System.out.println(printWordsWithPre(S1));*/
}
// Tokenises a string/sentence and prints only the words that starts with pre.
public static void printWordsWithPre(String str){
String[] sTokens = str.split("\\p{javaWhitespace}");
for(int i = 0; i < sTokens.length; i++){
//check if it starts with rather than ends with
if(sTokens[i].startsWith("pre")){
System.out.println(sTokens[i]);
}
}
}
}
我做了以下更改: