Java String to CharArray, hidden manner - java

I got another nooby question to Java gurus
Basically what I want is:
Take word;
Transform it to arrayOfChar;
Hide it to following manner: _ _ _ _;
I could get to to second step, however when I try to hide word in underscores it shows as ____ rather than _ _ _ _.
Code for it:
//Randomly picks word from Array which played
public String pickWord(){
String guessWord = (wordsList[new Random().nextInt(wordsList.length)]);
return guessWord;
}
//Hides picked word
public char[] setWord(){
word = pickWord().toCharArray();
for (int i = 0; i < Array.getLength (word); i++) {
word[i] = '_';
}
return word;
}

You will need to allow for the spaces in your new char array:
String testWord = "test";
char[] word = new char[testWord.length() * 2];
for (int i = 0; i < word.length; i+=2) {
word[i] = '_';
word[i + 1] = ' ';
}

When you store '' in word variable and print it it shows "__" because it shows consecutive '' . You can do it in various ways- like you can put a space every character of word or padding a space in word variable
for (int i = 0; i < Array.getLength (word); i++) {
word[2*i] = '_';
word[2*i+1] = ' ';
}

Add extra condition in for-loop
if(i%2 == 0)
word[i]='_';
else
word[i]=' ';
or simply override the word[i] only when i%2 =0. just one if block after you have
word[i]='_';
if(i%2 != 0)
word[i]=' ';

word = pickWord().toCharArray();
spacedWord = new char[word.length*2-1];
for (int i = 0; i < 2*word.length; i+=2) {
spacedWord[i] = '_';
spacedWord[i+1] = ' ';
}
return spacedWord;

Related

Replacing Duplicates in Character Array with placeholder character ' '?

For any string of characters I input to my charArray, this simply returns the first character and the rest as spaces. Why? I simply want to replace all of the non-original renditions of a character with a space.
for (int i = 0 ; i<charArray.length ; i++) {
for (int j = 1 ; j<charArray.length ; j++) {
if (charArray[i] == charArray[j])
charArray[j] = ' ';
}
}
Your inner loop needs to start at i + 1 instead of the hardcoded value 1:
char[] charArray = "abcdabce".toCharArray();
for (int i = 0; i < charArray.length; i++)
{
// check if a space was already inserted at this index
if (charArray[i] == ' ')
continue;
// check all remaining characters
for (int j = i + 1; j < charArray.length; j++)
{
if (charArray[i] == charArray[j])
{
charArray[j] = ' ';
}
}
}
System.out.println(charArray);
Output:
abcd e
To put it simply, this is what your code currently does:
For each character in the char array, if the same character appears somewhere in the array starting from the index 1, then change it to a space. This concretely means that all the characters starting from index 1 will be replaced (because the condition that they appear after index 0 will always be satisfied).
A simple example can illustrate why this won't actually work.
Suppose your input array is ['h','e','l','l','o'].
When i = 1 and j = 1, charArray[i] == charArray[j] will return true, thus your 'e' will be replaced by a space.
I would suggest looping through the array once, using a data structure that memorizes which characters previously appeared, which in this case corresponds to a Set.
Set<Character> charSet = new HashSet<>();
for (int i = 0; i < charArray.length; i ++) {
if (charSet.contains(charArray[i])) charArray[i] = ' ';
else charSet.add(charArray[i]);
}

How to add 2 words from an array to a string from another array

I am writing a mad lib program for school. The program must have 30 sentences, with two words from each sentence missing. I planned to store the sentences in an array, user-inputted words in a second array, and then add words from the word array to the sentences in the sentence array. When using for loops to do this, it works for the first sentence, but in every sentence after that the the same words are used.
Here's the code I have for this part:
String story[] = {"Once upon a time, there was a _ man named _.", "He loved playing _ on _ afternoons."};
String words[] = {"awesome", "James", "checkers", "Sunday"};
for (int i = 0; i < story.length; i++) {
for (int j = 0; j < words.length; j++) {
story[i] = story[i].replaceFirst(placeholder, words[j]); // placeholder is set to '_'
}
System.out.println(story[i]);
}
This should work
String story[] = {"Once upon a time, there was a _ man named _.", "He loved playing _ on _ afternoons."};
String words[] = {"awesome", "James", "checkers", "Sunday"};
int j=0;
for (int i = 0; i < story.length; i++) {
while(story[i].contains("_")){
story[i] = story[i].replaceFirst("_", words[j++]);
}
System.out.println(story[i]);
}
According to your case the words array will contain x2 elements more than story array. We can use that to write a simple algorithm:
String story[] = {"Once upon a time, there was a _ man named _.", "He loved playing _ on _ afternoons."};
String words[] = {"awesome", "James", "checkers", "Sunday"};
String placeholder = "_";
for (int i = 0; i < story.length; i++) {
String word1 = words[i * 2];
String word2 = words[i * 2 + 1];
story[i] = story[i]
.replaceFirst(placeholder, word1)
.replaceFirst(placeholder, word2);
System.out.println(story[i]);
}
This would work if you really solve it with this way:
for (int i = 0; i < story.length; i++) {
for (int j = i*2; j < (i*2)+1; j++) {
story[i] = story[i].replaceFirst(placeholder, words[j]); // placeholder is set to '_'
}
System.out.println(story[i]);
}

Nested for loop, not picking up first instance in Array

I am trying to encode a word, and I am not sure why my for loops aren't picking up the first instance, 0. The input for this method is "This" and 3. The output from this method is klv. So my loop must not be working properly as the letter T is getting skipped. What is wrong with my loops?
String encodeWord(String word, int Shift) {
//word = "This"
//Shift = 3, is how far the letter is shifted to the right of the original
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
char[] temp = word.toCharArray();
char[] FA = new char[temp.length];
String tempWord = "";
StringBuilder sb = new StringBuilder(64);
for (int x = 0; x < word.length(); x++) {
for (int y = 0; y < alphabet.length; y++) {
if (word.charAt(0) == alphabet[y]) {
FA[0] = alphabet[y + shift];
System.out.println(FA[0]);
}
}
}
for (int i = 0; i < word.length(); i++) {
for (int j = 0; j < alphabet.length; j++) {
if (word.charAt(i) == alphabet[j]) {
FA[i] = alphabet[j + shift];
sb.append(FA[i]);
System.out.println(FA[i]);
}
}
}
System.out.println(sb);
return sb.toString();
}
The letter 'T' is different from the letter 't', so since only the letter 't' is found in your array, the program won't find a match for the letter 'T'.
Another problem with your code is that you will get an Index out of bounds exception if the input contains the letters 'x', 'y' or 'z' because there aren't 3 letters after them in the array.
public static String encoder(String word, int shift)
{
static const int max_char = 122; //letter 'z'
static const int min_char = 97; //letter 'a'
char[] c_array = word.toCharArray();
char[] encoded_string = new char[c_arary.length()];
for(for i = 0; i < c_array.length(); i++)
{
if( ((int)c + shift) > max_char) //makes sure that the ascii isnt a non number
{
encoded_string[i] = (min_char + (int)c + shift - max_char ); // this will correct the overflow
}
c = c + shfit;
}
return encoded_string;
}
This is an easier way to do this... also your loops have a few logical errors.. the first one i caught was in the first loop... if there is a z in your word your going to overflow your alphabet array.
This is using the Ascii table way

Java program to find the letter that appears in the most words?

I have a sentence, and I want to find the char that appears in the most words, and how many words it appears in.
For example: "I like visiting my friend Will, who lives in Orlando, Florida."
Which should output I 8.
This is my code:
char maxChar2 = '\0';
int maxCount2 = 1;
for (int j=0; j<strs2.length; j++) {
int charCount = 1;
char localChar = '\0';
for (int k=0; k<strs2[j].length(); k++) {
if (strs2[j].charAt(k) != ' ' && strs2[j].charAt(k) != maxChar2) {
for (int l=k+1; l<strs2[j].length(); l++) {
if (strs2[j].charAt(k)==strs2[j].charAt(l)) {
localChar = strs2[j].charAt(k);
charCount++;
}
}
}
}
if (charCount > maxCount2) {
maxCount2 = charCount;
maxChar2 = localChar;
}
}
, where strs2 is a String array.
My program is giving me O 79. Also, uppercase and lowercase do not matter and avoid all punctuation.
As a tip, try using more meaningful variable names and proper indentation. This will help a lot especially when your program is not doing what you thought it should do. Also starting smaller and writing some tests for it will help a bunch. Instead of a full sentence, get it working for 2 words, then 3 words, then a more elaborate sentence.
Rewriting your code to be a bit more readable:
// Where sentence is: "I like".split(" ");
private static void getMostFrequentLetter(String[] sentence) {
char mostFrequentLetter = '\0';
int mostFrequentLetterCount = 1;
for (String word : sentence) {
int charCount = 1;
char localChar = '\0';
for (int wordIndex = 0; wordIndex < word.length(); wordIndex++) {
char currentLetter = word.charAt(wordIndex);
if (currentLetter != ' ' && currentLetter != mostFrequentLetter) {
for (int l = wordIndex + 1; l < word.length(); l++) {
char nextLetter = word.charAt(l);
if (currentLetter == nextLetter) {
localChar = currentLetter;
charCount++;
}
}
}
}
if (charCount > mostFrequentLetterCount) {
mostFrequentLetterCount = charCount;
mostFrequentLetter = localChar;
}
}
}
Now all I did was rename your variables and change your for loop to a for-each loop. By doing this you can see more clearly your algorithm and what you're trying to do. Basically you're going through each word and comparing the current letter with the next letter to check for duplicates. If I run this with "I like" i should get i 2 but instead I get null char 1. You aren't properly comparing and saving common letters. This isn't giving you the answer, but I hope this makes it more clear what your code is doing so you can fix it.
Here is a somewhat more elegant solution
public static void FindMostPopularCharacter(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
char occursTheMost = 'A'; //start with default most popular char
int maxCount = 0;
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
//first find the character to look for
for(int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
//if contained in our map increment its count
if(charData.containsKey(c))
charData.put(c, charData.get(c) + 1);
//check for a max count and set the values accordingly
if(charData.containsKey(c) && charData.get(c) > maxCount)
{
occursTheMost = c;
maxCount = charData.get(c);
}
}
//final step
//now split it up into words and search which contain our most popular character
String[] words = input.split(" ");
int wordCount = 0;
CharSequence charSequence;
for(Character character : charData.keySet())
{
int tempCount = 0;
charSequence = "" + character;
for(int i = 0; i < words.length; i++)
{
if(words[i].contains(charSequence))
tempCount++;
}
if(tempCount > wordCount)
{
occursTheMost = character;
wordCount = tempCount;
}
}
System.out.println(occursTheMost + " " + wordCount);
}
Output of
String input = "I like visiting my friend Will, who lives in Orlando, Florida.";
FindMostPopularCharacter(input);
is
I 8
Note: If there are ties this will only output the character that first reaches the maximum number of occurrences.
FindMostPopularCharacter("aabb aabb aabb bbaa");
Outputs
B 4
because B reaches the max first before A due to the last word in the input.
FindMostPopularCharacter("aab aab b")
B 3

Replacing characters of a string in a particular sequence

The String word contains a character ] at more than one place. I want to replace any character before the ] by l, and any character after by r.
For example, the String defined below:
String word="S]RG-M]P";
Should be converted to:
String word="l]rG-l]r";
When I tried by the following code:
String word="S]RG-M]P";
char[] a = word.toCharArray();
for(int i=0; i<a.length; i++){
if (a[i]==']'){
a[i+1]='r';
a[i-1]='l';
}
}
It changes the right side of ] by r, but fails left to it by l. I need help to get the required results.
public static void main(String[] args) {
String word = "S]RG-M]P";
char[] a = word.toCharArray();
for (int i = 1; i < a.length-1; i++) {//#Jon Skeet again is right X2 :)
//no need now, for loop bound changed
//if(i+1>a.length){
// continue;
// }
if (a[i] == ']') {
//no need now, for loop bound changed
//#Jon Skeet you are right, this handles the case :)
//if(i==0 || i == a.length-1){
//continue;
//}
a[i + 1] = 'r';
a[i - 1] = 'l';
}
}
String outt = new String(a);
System.out.print(outt);
}// main
StringBuilder word = new StringBuilder("S]RG-M]P");
int index = word.indexOf("]");
while(index > 0){
word.setCharAt(index-1, 'l');
word.setCharAt(index+1, 'r');
index = word.indexOf("]", index+1);
}
System.out.println(word);
String word="S]RG-M]P";
word.replaceAll(".]." , "l]r");
using regex and string methods is useful in this situation
for(int i=0 ; i<word.length();i++){
char a = word.charAt(i);
String after =null;
if( Character.toString(a).equals("]")){
int j = i-1;
int k = i+1;
char b = word.charAt(j);
char c = word.charAt(k);
modifyword= word.replace( Character.valueOf(b).toString(), "l");
after= modifyword.replace( Character.valueOf(c).toString(), "r");
word = after;
}
}

Categories