Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I was wondering what the highlighted parts did in the code... I just want to kno

ID: 3545530 • 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)

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

The need of square brackets there is for regular expression. In this context it is looking if the first character of the sting matches with any of the following [aeiouAEIOU] character.






String.split(" ") chops the string into a string array exactly at the occurence of a space.


A simple implementation of the function can be thought about as




String[] split(String splitter)

{


char[] c=str.toCharArray();

String[] words=new String[1000];

int count=0;


String word;



for(int i=0;i<c.len;i++)

{


if(c[i]==new Character(splitter))

{

words[count]=word;

word="";

count++;

}


else

{

word+=new String(c[i]);

}

}


return words;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote