Imprimer les mots uniquement en commençant par en commençant par pre Java
Créer une classe StringDemo qui contient les méthodes statiques suivantes: * Une méthode qui prend une phrase, la tokenise en utilisant un seul espace, puis imprime uniquement les mots qui commencent par "pre". * La méthode principale où vous déclarez 2 variables et les initialisez aux phrases de votre choix; puis testez la méthode que vous avez définie à l'étape précédente en utilisant les 2 phrases.
Ma tentative
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
Author: Ryan Clarke, 2018-04-11
2 answers
Essayez le code suivant:
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]);
}
}
}
}
J'ai apporté les modifications suivantes:
- Ajout de quelques mots commençant par pre;
- Supprimé le système.hors.println's en principal parce qu'ils ont essayé d'imprimer un retour vide;
- fin changée avec pour startsWith.
2
Author: Mateus Terra, 2018-04-11 19:02:04
Vous avez utilisé endsWith
au lieu de startsWith
2
Author: Bogdan Lukiyanchuk, 2018-04-11 18:50:50