Question:
HollePrinter.java, how to do?
JDOGG
2008-09-08 09:31:56 UTC
"Write a program HollePrinter that switches the letters "e" and "o" in a string. Use the replace method repeatedly. Demonstrate that the string "Hello, World!" turns into "Holle, Werld!"
Three answers:
Andy G
2008-09-08 10:14:27 UTC
Really sounds like a homework question. As the question tells you how to write the solution. The real trick here is to preserve one of the letters while changing the other. One way to do this would be to first preserve one of the characters with something that is not in the string. The choice of this temporary character should be made so that it is not the same as any in the string that's being processed.



Selecting a character to do can be done by analyzing the string or selecting a character that is never going to be present. Bear in mind Java characters support Unicode. So it would be valid to replace your character with a little used Unicode character. eg



....

yourString = yourString.replace("e","\u2603");

yourString = yourString.replace("o","e");

yourString = yourString.replace("\u2603","o");

...







The best way to demonstrate that your program works is to use a Junit test case.





Addition:



- If your instructor wouldn't believe that you would think of using unicode you could equally pick a character that you don't expect in the string. That might be a symbol character or a usually untypeable character low in the ASCII table. If you wanted to explain the use of the unicode, you don't need to go any further than the javadoc for Character which mentions unicode.

- You might get better marks if you think about reuse.

- Your solution of replacing He with Ho is likely to get you a lower grade as it is not general purpose. "Hello World" is your test data for a function that replaces characters in strings.



One possible design would be to think about classes like Math, which just contains lots of static methods. Classes like these have a number of properties: which modern IDEs will highlight for you. The class is final and the constructor is private, preventing extending and construction.



public final class StringHelper {

private StringHelper () { }



public String swapCharacters(String inString,char first,char second) {

....

}

}



Demonstration can then be within a main() method as you have done, or with a unit test case. See Junit link. Consider something like



@Test

public void testHelloWorld()

{ assertEquals("HolleWerld",

StringHelper.swapCharacters("HelloWorld",'e','o'));

}
Jim Maryland
2008-09-08 10:31:08 UTC
You could always use the String.subSequence(int beginIndex, int endIndex) method to get a CharSequence object that you can the loop through to change the "e" and "o" values around. On the CharSequence object, setup your loop to use the CharSequence.length() for a bound and walk through checking for "e" and "o" and change as needed. You could build a new String or simply print it to the console (without a newline).



** Edit **

Given that this is a homework problem, people generally answer very specific portions to help you learn. If we provided a complete answer, how does that really help you? You will need at least one class with a main method to write your application. If you really want to break it out, you'd probably write at least two classes with one being your main application and the other being a replace characters class that had a method signature like:



String ReplaceChars.replace(HashMap replaceMap, String inString)



That method would then use the HashMap key/value to process the "inString" and ultimately return the String to the caller of the method on the object. Doing it this way makes your class reusable and flexible, but probably goes beyond what your teacher is looking for.
deonejuan
2008-09-08 13:38:14 UTC
Oh, I looked at this several ways. I hesitate to give you my code because your instructor will know you didn't do it. But, here it is. You will note I look for the e's and record the numeric positions. I then change the o's. I take the new String with the o's, make a StringBuffer. With my numeric positions, I change the e's to o's. I then change the StringBuffer back to a String.



I couldn't never do a double-pass using .replace('e','o'); .replace('o','e'). Using subsequence turns into a mudball.



==============

import java.util.Scanner;



/**

* Created on Sep 8, 2008, 7:44:25 PM

*

* @author vjuan

*/

public class StringSwapChar {



// the constructor of the class

public StringSwapChar() {



// when a new class Object is created, do the method

intro();

}



public static void main( String[] args ) {

// one gets state, values, methods() with an Object

// the keyword 'new' makes an Object into memory



new StringSwapChar();



// most of the time you see a 'label' attached to

// manfacture a var label. I could do so...

// StringSwapChart ssc = new StringSwapChart();

// but then, I'd have to access everything like this

// ssc.run ... or ssc.swapOE( ssc.s )

}







// methods

private String swapOE( String s ) {

String ndexes = "";



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

int c = Integer.valueOf(s.charAt(i));

int ee = Integer.valueOf('e');

ndexes += (c == ee ) ? String.valueOf(i)+"," : "";



}

ndexes =

ndexes.substring(

0,ndexes.lastIndexOf(","));

// mess(ndexes+"\n");

String newSe = s.replace('o', 'e');



String newSo = swapEO( newSe, ndexes );



return newSo;

}

private String swapEO( String s, String dex ) {

String[] ndexes = dex.split(",");

StringBuffer sb = new StringBuffer(s);

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

sb.setCharAt( Integer.valueOf(ndexes[i]) , 'o');



}

String newString = sb.toString();



return newString;

}

private void mess( String s ) {

System.out.print( s );

}

private boolean ending( Scanner scanner ) {

boolean keepGoing = true;

System.out.print("Enter another String? ");



keepGoing =

scanner.nextLine().

equalsIgnoreCase("y");

if( !keepGoing ) {

// if false print bye bye

mess("Bye! User typed \"N\"\n");

}

else

mess("User typed \"Y\"\n\n");



return keepGoing;

}

private void intro() {

boolean run = true;

Scanner sc = new Scanner( System.in );

while( run ) {

mess("Input a String: ");

String input = sc.nextLine();

mess( swapOE(input) + "\n" );



run = ending(sc);

}

}

}



////////////////

if there was a shorter way without using RegEx, I'd like to see the code



good luck


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...