Click to See Complete Forum and Search --> : Using a Switch


Khoulod Khalid
March 5th, 2000, 04:38 PM
i have an assignment where i have to set a variable to hold a sentence and printout the sentence in code, substituting a new character for each character in the sentence. i'm not supposed to use the string replace()method, but i should use a switch statement. can someone help me in figuring out the solution?
thanks in advance..

mjpell
March 8th, 2000, 02:29 PM
I would probably look at the StringBuffer class, and maybe use replace(..) or setCharAt(..) methods.

I'm not sure what a switch has to do with anything. Unless you want to use a switch/case statement to decide what to replace the char with. The switch statement can be used similarly as an if/else statement, only faster and nicer.

good luck,

DHunter21
March 8th, 2000, 05:15 PM
A rather rudimentary way, but it should probably look something like:

String message;
...

public String encodeMessage(String message){
char[] encoded = message.getChars();
for(int i = 0; i<encoded.length; i++){
switch(encoded[i]){
case('a'): encoded[i] = 'f'; break;
case('b'): encoded[i] = 'x'; break;
....
}
}
return new String(encoded);

}




Hope this helps.

Dustin