I have this
public class Mapper implements ScramblerIF
{
private static String map = "drsjckpwrypwsftylmzxopqtdo";
public static String charAt(String str)
{
//char[] chars = str.toCharArray();
int length = str.length();
for(int i=0; i<length; i++)
{
char aChar = str.charAt(i);
char upper = Character.toUpperCase(aChar);
int num = (upper - 'A');
char mChar = map.charAt(num);
//String chard = Character.toString(mChar);
StringBuffer buf = new StringBuffer( str);
buf.setCharAt( i, mChar );
}
return str;
}
public String scramble(String str) {
return charAt(str);
}
}
I am trying to get it to where the method
public String scramble(String str) {
return charAt(str);
}
returns the computed value from the
public static String charAt(String str)
method. Don't know where i went wrong.
Also instead of using
StringBuffer buf = new StringBuffer( str);
buf.setCharAt( i, mChar );
how would i be able to use the swap function? When I try
char temp = chars[i];
chars[i] = chars[mChar];
chars[mChar] = temp;
I am given an ArrayIndexOutOfBoundsException. Summary of what i am trying to do is "For each character in the original string, use its position in the alphabet to look up its replacement in the map string. For example, the string “dog” would be translated to “jtp”."
This scrables with the replacement-map you have provided. It also handles upper and lower case letters:
public class Mapper {
// abcdefghijklmnopqrstuvwxyz
private static String map = "drsjckpwrypwsftylmzxopqtdo";
public static String scramble(String str) {
if (!str.matches("[A-Za-z]*"))
throw new RuntimeException(str + " contains weird characters");
String out = "";
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c)) {
out += Character.toUpperCase(map.charAt(c - 'A'));
} else {
out += map.charAt(c - 'a');
}
}
return out;
}
public static void main(String[] args) {
System.out.println(scramble("David"));
}
}
StringBuffer.setCharAt() will throw an exception if you try to set a character beyond the buffer. You haven't put anything in the buffer.
In addition, take a look at when you are creating the buffer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.