I was wondering what the highlighted parts did in the code... I just want to kno
ID: 3545588 • 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(" "); ------- How does this else method work?
for(String token : tokens) ------- How does this else method work?
printLatinWord(token); -------- How does this work?
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
1) String[] tokens = phrase.split(" "); ------- How does this else method work?
Ans:- Here the split function will break the string into each word because delimiter for parameter in split function is " " (a blank).So on the basis of blank or whitspace it will break String.
2)for(String token : tokens) ------- How does this else method work?
Ans:- It is a new of writing for loop in java instead of traditional for( ; ; )loop.
it will read each member of array "tokens" until it reach end of array.
Example:- int arr[ ] = {1,2,3};
for(int i ; arr){
System.out.println(i);
}
it will print 1 2 3.
3) if(word.substring(0,1).matches("[aeiouAEIOU]")){ ------ Why does there need to be square brackets?
Ans:- here the square bracket represents that parameter we are passing is regular expression .
if() condition will be true if the first letter of word matches with any of the letter given in [aeiouAEIOU]...either a or e or i or o or u or A or E ...etc. like in this way.
4) printLatinWord(token); -------- How does this work?
Ans:-it only include if() condition which will be true if a word start with vowel otherwise it will be false
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.