0% found this document useful (0 votes)
8 views

Lab6a Explain

The document discusses randomly generating phrases by replacing letters in a given string with asterisks. It also describes two ways to handle replacing repeated letters when a user inputs a character - replacing all occurrences at once, or replacing them one by one and tracking replaced indexes.

Uploaded by

Henry
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lab6a Explain

The document discusses randomly generating phrases by replacing letters in a given string with asterisks. It also describes two ways to handle replacing repeated letters when a user inputs a character - replacing all occurrences at once, or replacing them one by one and tracking replaced indexes.

Uploaded by

Henry
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

LabExer6A explain

// randomly generating the phrase


// instead of having hard coded value like this , StringBuilder phrase = new
StringBuilder("***E O* ***O*E*");

// we can randomly create the phrase

StringBuilder phrase = generatePhrase(str)'

import java.util.Random;

public static void generatePhrase(String[] str)

StringBuilder phrase = new StringBuilder(str)

Random r1 = new Random();

int numberOfChars = r1.nextInt(str.length()-1); // randomly creating


a integer for how many characters to be replace

int index = 0;

for (int i = 0; i < numberOfChars; i++)

index = r1.nextInt(str.length()-1);
// then randomly creating a integer, for index value of string, for letter to
replace by *

phrase.replace(index,index+1,"*");

return phrase;

2. // another modification can be done for replacing the repeated characters

// case 1: if all repeated letters changed by single input of user. like if


user is putting 'E' or 'O' , then it should replace both the E or O.

then in that case we can use for loop to traverse thru out length and replace all
the charactars
public static int placeLocator(char input, String phraseSolution, StringBuilder
phrase)

int place;

int x = 0;

for(i=0;i<phraseSolution.length();i++)

if(input == phraseSolution.charAt(i))

phrase.setCharAt(i, input); //changing letter of phrase

//case2 : if repeated characters not to be replace in one go. in that case we need
to create the array of bool values . this array will be used to create the track of
index which is changed....

Boolean[] array1 = new Boolean[phrase.length()]

public static int placeLocator(char input, String phraseSolution, StringBuilder


phrase)

for(int i=0;i<phraseSolution.length();i++)

if(input == phraseSolution.charAt(i) && !array1[i])

phrase.setCharAt(i, input); //changing letter of phrase

array1[i] = True

}
}

You might also like