I was wondering what the highlighted parts did in the code... I just want to kno
ID: 3545467 • Letter: I
Question
I was wondering what the highlighted parts did in the code... I just want to know why they work and how it does it. This would help me out a great deal. Thank you.
String phrase;
Scanner input = new Scanner(System.in);
while(true)
{
System.out.println("Enter a phrase: ");
phrase = input.nextLine();
if(phrase.equals(""))
{
System.out.println("Program Terminated");
break;
}
else
{
String[] tokens = phrase.split(" ");
for(String token : tokens)
printLatinWord(token);
System.out.println();
}
}
}
public static void printLatinWord(String word)
{
String pigLatin = "ay";
if(word.substring(0,1).matches("[aeiouAEIOU]")){ ------ Why does there need to be square brackets?
System.out.printf("%s-%s ",word,pigLatin);
} else {
System.out.printf("%s-%s%s ",word.substring(1),word.charAt(0),pigLatin);
}
}
}
Explanation / Answer
if(word.substring(0,1).matches("[aeiouAEIOU]")) - match method of java uses a regular expressions.
The intention of the programmer was to compare the starting letter of word to any of the characters that are enclosed with in the Square brackets.
the condition will return true if the word starts with any of the characters a,e,i,o,u,A,E,I,O or U.
The square brackets indicates that Match any single character in the brackets.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.