-
Using a Switch
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..
-
Re: Using a Switch
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,
-
Re: Using a Switch
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