Encode/Decode Script that decodes and encoded string twice - java

Basically have a simple process that involves mapping letters and numbers 2 spaces forward so an A would encode to C , 1 to 3 and such. There is wraparound for so Z would encode to B and 0 would encode to 2. The encode works fine, but after the first cycle of the loop the decode seems to map back 4 spaces instead of 2. Here's the code, let me know what you guys think the problem is.
Encode/Decode
public class EncodeDecode {
private String[] originalList;
private String[] encodedList;
private String[] decodedList;
public EncodeDecode(String[] oL) {
originalList = oL;
encodedList = originalList;
decodedList = originalList;
for (int cnt = 0; cnt < oL.length; cnt++) {
encodedList[cnt] = originalList[cnt];
}
for (int cnt = 0; cnt < oL.length; cnt++) {
decodedList[cnt] = originalList[cnt];
}
}
public String encode(String originalWord) {
//Maps every character in original word to 2 positions forward w/ wrap around.
String result = "";
for (int cnt = 0; cnt < originalWord.length(); cnt++) {
result += forwardMap(originalWord.charAt(cnt));
}
encodedList[0] = result;
return result;
}
public String decode(String codedWord) {
//Maps every character back 2 spaces w/ wrap around
String result = "";
for (int cnt = 0; cnt < codedWord.length(); cnt++) {
result += backMap(codedWord.charAt(cnt));
}
decodedList[0] = result;
return result;
}
public char forwardMap(char ch) {
char result = Character.toLowerCase(ch);
if (result == 'a') return 'c';
if (result == 'b') return 'd';
if (result == 'c') return 'e';
if (result == 'd') return 'f';
if (result == 'e') return 'g';
if (result == 'f') return 'h';
if (result == 'g') return 'i';
if (result == 'h') return 'j';
if (result == 'i') return 'k';
if (result == 'j') return 'l';
if (result == 'k') return 'm';
if (result == 'l') return 'n';
if (result == 'm') return 'o';
if (result == 'n') return 'p';
if (result == 'o') return 'q';
if (result == 'p') return 'r';
if (result == 'q') return 's';
if (result == 'r') return 't';
if (result == 's') return 'u';
if (result == 't') return 'v';
if (result == 'u') return 'w';
if (result == 'v') return 'x';
if (result == 'w') return 'y';
if (result == 'x') return 'z';
if (result == 'y') return 'a';
if (result == 'z') return 'b';
if (result == '0') return '2';
if (result == '1') return '3';
if (result == '2') return '4';
if (result == '3') return '5';
if (result == '4') return '6';
if (result == '5') return '7';
if (result == '6') return '8';
if (result == '7') return '9';
if (result == '8') return '0';
if (result == '9') return '1';
if (result == ' ')
return ' ';
else
return '$';
}
public char backMap(char ch) {
char result = Character.toLowerCase(ch);
if (result == 'c') return 'a';
if (result == 'd') return 'b';
if (result == 'e') return 'c';
if (result == 'f') return 'd';
if (result == 'g') return 'e';
if (result == 'h') return 'f';
if (result == 'i') return 'g';
if (result == 'j') return 'h';
if (result == 'k') return 'i';
if (result == 'l') return 'j';
if (result == 'm') return 'k';
if (result == 'n') return 'l';
if (result == 'o') return 'm';
if (result == 'p') return 'n';
if (result == 'q') return 'o';
if (result == 'r') return 'p';
if (result == 's') return 'q';
if (result == 't') return 'r';
if (result == 'u') return 's';
if (result == 'v') return 't';
if (result == 'w') return 'u';
if (result == 'x') return 'v';
if (result == 'y') return 'w';
if (result == 'z') return 'x';
if (result == 'a') return 'y';
if (result == 'b') return 'z';
if (result == '2') return '0';
if (result == '3') return '1';
if (result == '4') return '2';
if (result == '5') return '3';
if (result == '6') return '4';
if (result == '7') return '5';
if (result == '8') return '6';
if (result == '9') return '7';
if (result == '0') return '8';
if (result == '1') return '9';
if (result == ' ')
return ' ';
else
return '$';
}
public String[] getEncodedList() {
return encodedList;
}
public String[] getDecodedList() {
return decodedList;
}
}
Tester
public class EncodeDecodeTester {
public static void main(String[] args) {
String[] list = {"abcd", "abcd", "abcd"};
EncodeDecode ec = new EncodeDecode(list);
String[] encode = ec.getEncodedList();
for (int index = 0; index < encode.length; index++) {
System.out.println("Encoded: " +ec.encode(list[index]));
System.out.println("Decoded: " +ec.decode(list[index]));
}
}
}

The first thing I notice is object references on String[], change this
encodedList = originalList;
decodedList = originalList;
to
encodedList = new String[originalList.length];
decodedList = new String[originalList.length];

NOtice that in your main function you are calling a decode on the actual string and not on the encoded string. so your program is working properly if the initializations are correct as Elliot pointed.
for (int index = 0; index < encode.length; index++)
{
System.out.println("Encoded: " +ec.encode(list[index]));
System.out.println("Decoded: " +ec.decode(ec.encode(list[index])));
}
and that will give you your desired output

Ending up finding the answer after enough tinkering around with things and bouncing ideas off my roommates.
Changed this:
public String decode(String codedWord)
{
//Maps every character back 2 spaces w/ wrap around
String result = "";
for (int cnt = 0; cnt < codedWord.length(); cnt++)
{
result += backMap(codedWord.charAt(cnt));
}
decodedList[0] = result;
return result;
}
To this:
public String decode(String codedWord)
{
//Maps every character back 2 spaces w/ wrap around
String result = "";
for (int cnt = 0; cnt < codedWord.length(); cnt++)
{
result += backMap(encodedList[0].charAt(cnt));
}
decodedList[0] = result;
return result;
}

Related

Recursive method to evaluate expressions just work when method is called once

I'm writing a code to valuate math expressions. The code just works when I call the methode once. But I have more than one expression to evaluate and it just break when I call the method more than two times. I get the following error:
-2
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at java.util.Stack.pop(Stack.java:84)
at Evaluate.parse(Evaluate.java:58)
at Evaluate.main(Evaluate.java:11)
I see that the code gives me the expected result (the -2) but what I'm doing wrong regarding the methode that gives me this error
My code:
public class Evaluate {
static Stack<Character> ops = new Stack<Character>();
static Stack<Integer> vals = new Stack<Integer>();
static int i = 0;
public static void main(String[] args) {
System.out.println(parse("(4-(7-1))"));
System.out.println(parse("8"));
System.out.println(parse("((1+1)*(2*2))"));
System.out.print("\n");
System.out.println(parse("(6/(3/2))"));
}
private static int parse(String expression) {
char[] tokens = expression.toCharArray();
while (tokens.length > i) {
char s = tokens[i];
if (s == '(') {
ops.push(tokens[i]);
} else if (s == '+' || s == '-' || s == '*' || s == '/') {
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
ops.push(s);
} else if (s == ')') {
char op = ops.pop();
int v = vals.pop();
while (ops.peek() != '(')
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
ops.pop();
if (op == '+') {
v = vals.pop() + v;
} else if (op == '-') {
v = vals.pop() - v;
} else if (op == '*') {
v = vals.pop() * v;
} else if (op == '/') {
v = vals.pop() / v;
}
vals.push(v);
} else {
vals.push(Character.getNumericValue(s));
}
i++;
}
while (!ops.empty())
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
return vals.pop();
}
public static boolean hasPrecedence(char op1, char op2) {
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an
// operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op, int b, int a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}

Operator changed to int during infix to postfix conversion

private DSAQueue parseInfixToPostfix(String equation) {
String result = "";
char operator = ' ';
DSAStack stack = new DSAStack();
DSAQueue queue = new DSACircular();
for (int i = 0; i < equation.length(); i++) {
char c = equation.charAt(i);
if (Character.isLetterOrDigit(c)) {
result += c;
}
else if (c == '(') {
stack.push(c);
}
else if (c == ')') {
while (!stack.isEmpty() && stack.top() != '(') {
result += stack.pop();
}
if (!stack.isEmpty() && stack.top() != '(') {
result = "Invalid expression";
}
else {
stack.pop();
}
}
else { //when meets operator
while (!stack.isEmpty() && (precedenceOf(c) <= precedenceOf((char) stack.top()))) {
if (stack.top() == '(') {
result = "Invalid expression";
}
result += stack.pop();
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
if (stack.top() == '(') {
result = "Invalid";
}
result += stack.pop();
}
queue.enqueue(result);
return queue;
}
Above is my code for converting infix to postfix. The example i used is "4+2" and what i got is:
Pushed: 43
Popped: 43
Enqueued: 4243
i dont know why it automatically converted "+" to 43, but i want to store the operator as the operator like "+" in the queue. Is it possible? Or is there an error? because i cant find out what the error is. thank you

How to use a Boolean variable when reading through user input

In my code, I am creating a window where a user can input a phrase. I am then setting up a for loop to read through the input and add ub before any vowel. My problem now is that if the user input is aeiou the output I want is ubaeiou and not ubaubeubiuboubu. I believe a Boolean variable would help but I am stuck on how to do this portion.
public void buttonPressed() {
String line = input1.getText();
String finline;
finline = "";
line = line.toLowerCase();
for(int i =0; i < line.length(); i++) {
if((line.charAt(i) == 'a') || (line.charAt(i) == 'e') || (line.charAt(i) == 'i') || (line.charAt(i) == 'o') || (line.charAt(i) == 'u'))
{
finline = finline + "ub" + line.charAt(i);
}
else
{
finline = finline + line.charAt(i);
}
}
output.setText(finline);
}
User input = aeiou
Output = ubaubeubiuboubu
Desired output = ubaeiou
You want the "ub" prefix on the first vowel of the LINE? Then use a boolean to trigger an early loop exit.
public void buttonPressed() {
Boolean done = false;
String line = input1.getText();
String finline;
finline = "";
line = line.toLowerCase();
for(int i =0; i < line.length() && !done; i++) {
if((line.charAt(i) == 'a') || (line.charAt(i) == 'e') || (line.charAt(i) == 'i') || (line.charAt(i) == 'o') || (line.charAt(i) == 'u'))
{
finline = finline + "ub" + line.charAt(i);
done = true;
}
else
{
finline = finline + line.charAt(i);
}
}
output.setText(finline);
}
Or if you want it on the first vowel of EACH WORD, you'll need to work the boolean into the vowel check condition and make sure it gets turned off on word breaks.
public void buttonPressed() {
Boolean checkVowel = true;
String line = input1.getText();
String finline;
finline = "";
line = line.toLowerCase();
for(int i =0; i < line.length(); i++) {
if(checkVowel && ((line.charAt(i) == 'a') || (line.charAt(i) == 'e') || (line.charAt(i) == 'i') || (line.charAt(i) == 'o') || (line.charAt(i) == 'u')))
{
finline = finline + "ub" + line.charAt(i);
checkVowel = false;
}
else
{
finline = finline + line.charAt(i);
if (line.charAt(i) == ' ') checkVowel = true;
}
}
output.setText(finline);
}
try this:
String line = "aeiou";
String finline;
finline = "";
line = line.toLowerCase();
Boolean flag = true;
for (int i = 0; i < line.length(); i++) {
Boolean flagLine = (line.charAt(i) == 'a') || (line.charAt(i) == 'e') || (line.charAt(i) == 'i') || (line.charAt(i) == 'o')
|| (line.charAt(i) == 'u');
if (flag && flagLine) {
finline = finline + "ub" + String.valueOf(line.charAt(i));
flag = false;
}
else {
if(!flagLine) flag = true;
finline = finline + String.valueOf(line.charAt(i));
}
}
System.out.println(finline);
input = aeiou
output = ubaeiou
input = aeqou
output = ubaequbou

Special characters in a string [JAVA]

folks, the method below would throw an Exception if other character than "01xX \t"(including whitespace and \t inside a passed String) is found. If I have this String "1 x \tX 00", the method should return [1,X,X,X,X,X,X,X,0,0] but Im getting only [1,X,X,0,0] in which the 'whitespace' and '\t' somehow are not getting included. 'Whitespace' and '\n' also should return 'X'. Please could smb help me?
//Here's the test case that I'm failing
#Test (timeout=3000) public void signal13(){
String inp = "1 x \tX 00";
List<Signal> expecteds = Signal.fromString(inp);
assertEquals(expecteds, Arrays.asList(new Signal[]{Signal.HI, Signal.X, Signal.X, Signal.LO, Signal.LO}));
}
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public enum Signal {
HI, LO, X;
public Signal invert()
{
if(this == HI)
return LO;
else if(this == LO)
return HI;
else if(this == X)
return X;
return this;
}
public static Signal fromString(char c)
{
if(c == '1')
return HI;
else if(c == '0')
return LO;
else if(c == 'X')
return X;
else if(c == 'x')
return X;
else
throw new ExceptionLogicMalformedSignal(c, "Invalid character!");
}
public static List <Signal> fromString(String inps)
{
List<Signal> values = new ArrayList<Signal>();
for(int i = 0; i < inps.length(); i++)
{
if(inps.charAt(i) == '1')
values.add(HI);
else if(inps.charAt(i) == '0')
values.add(LO);
else if(inps.charAt(i) == 'X')
values.add(X);
else if(inps.charAt(i) == 'x')
values.add(X);
else if(inps.charAt(i) == ' ')
values.add(X);
else if(inps.charAt(i) == '\t')
{
values.add(X);
values.add(X);
}
else
throw new ExceptionLogicMalformedSignal(inps.charAt(0), "Invalid character!");
}
return values;
}
#Override
public String toString()
{
if(this == HI)
return "1";
else if(this == LO)
return "0";
else if(this == X)
return "X";
return "Error here!";
}
public static String toString(List<Signal> sig)
{
String result = "";
ArrayList<Signal> temp = new ArrayList<>();
for(Signal x: sig)
{
temp.add(x);
}
for(int i = 0; i < temp.size(); i++)
{
if(temp.get(i) == HI)
result += "1";
else if(temp.get(i) == LO)
result += "0";
else if(temp.get(i) == X)
result += "X";
}
return result;
}
}
Seem like the assertion is not correct, it's:
assertEquals(expecteds, Arrays.asList(new Signal[]{Signal.HI, Signal.X, Signal.X, Signal.LO, Signal.LO}));
while it should be :
List<Signal> actual = Signal.fromString(inp);
List<Signal> expected = Arrays.asList(new Signal[]{Signal.HI, Signal.X, Signal.X,Signal.X,Signal.X,Signal.X,Signal.X,Signal.X, Signal.LO, Signal.LO});
assertEquals(expected, actual);
Because the expected result is [1,X,X,X,X,X,X,X,0,0]
here is a modified version of your code that works as you need it...
private String fromString(String inps) throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inps.length(); i++) {
if (inps.charAt(i) == '1') {
sb.append("1");
} else if (inps.charAt(i) == '0') {
sb.append("0");
} else if (inps.charAt(i) == 'X') {
sb.append("x");
} else if (inps.charAt(i) == 'x') {
sb.append("x");
} else if (inps.charAt(i) == ' ') {
sb.append("x");
} else if (inps.charAt(i) == '\t') {
sb.append("x");
sb.append("x");
} else {
throw new Exception("invalid character");
}
}
return sb.toString();
}
When you output fromString("1 x \tX 00") you get the result 1xxxxxxx00 as expected.
Hope this helps

How to remove spaces from blackberry URL [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Blackberry URL encoder
i am using
String url="http://xxxxxx.com/api/api.php?func=xxxxxxxxxxxx&params[]="+searchText+CustomUtility.getConnectionString();
HttpConnection conn=(HttpConnection)Connector.open(url);
InputStream in=(InputStream)conn.openInputStream();
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
parser.parse(in, new ContactParser());
problem is this when searchText has many spaces it is not working , so please how i can remove spaces from URL
try this -
URLUTF8Encoder.enceode(searchText);
URLUTF8Encoder class is given below-
public class URLUTF8Encoder {
final static String[] hex = {
"%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
"%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F",
"%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
"%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F",
"%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27",
"%28", "%29", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F",
"%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37",
"%38", "%39", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F",
"%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47",
"%48", "%49", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F",
"%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57",
"%58", "%59", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F",
"%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67",
"%68", "%69", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F",
"%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77",
"%78", "%79", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F",
"%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87",
"%88", "%89", "%8A", "%8B", "%8C", "%8D", "%8E", "%8F",
"%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97",
"%98", "%99", "%9A", "%9B", "%9C", "%9D", "%9E", "%9F",
"%A0", "%A1", "%A2", "%A3", "%A4", "%A5", "%A6", "%A7",
"%A8", "%A9", "%AA", "%AB", "%AC", "%AD", "%AE", "%AF",
"%B0", "%B1", "%B2", "%B3", "%B4", "%B5", "%B6", "%B7",
"%B8", "%B9", "%BA", "%BB", "%BC", "%BD", "%BE", "%BF",
"%C0", "%C1", "%C2", "%C3", "%C4", "%C5", "%C6", "%C7",
"%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF",
"%D0", "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D7",
"%D8", "%D9", "%DA", "%DB", "%DC", "%DD", "%DE", "%DF",
"%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", "%E7",
"%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF",
"%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6", "%F7",
"%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE", "%FF"
};
public static String encode(String s)
{
StringBuffer sbuf = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i++) {
int ch = s.charAt(i);
if ('A' <= ch && ch <= 'Z') { // 'A'..'Z'
sbuf.append((char)ch);
} else if ('a' <= ch && ch <= 'z') { // 'a'..'z'
sbuf.append((char)ch);
} else if ('0' <= ch && ch <= '9') { // '0'..'9'
sbuf.append((char)ch);
} else if (ch == ' ') { // space
//sbuf.append('+');
sbuf.append("%20");
} else if (ch == '!') {
sbuf.append("%21");
} else if (ch == '*') {
sbuf.append("%2A");
} else if (ch == '(') {
sbuf.append("%28");
} else if (ch == ')') {
sbuf.append("%29");
} else if (ch == '\'') {
sbuf.append("%27");
} else if (ch == '-' || ch == '_' // unreserved
|| ch == '.'
|| ch == '~' || ch == '\'') {
sbuf.append((char)ch);
} else if (ch <= 0x007f) { // other ASCII
sbuf.append(hex[ch]);
} else if (ch <= 0x07FF) { // non-ASCII <= 0x7FF
sbuf.append(hex[0xc0 | (ch >> 6)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
} else { // 0x7FF < ch <= 0xFFFF
sbuf.append(hex[0xe0 | (ch >> 12)]);
sbuf.append(hex[0x80 | ((ch >> 6) & 0x3F)]);
sbuf.append(hex[0x80 | (ch & 0x3F)]);
}
}
return sbuf.toString();
}
}
you can use the below code to remove white space character in a given string ,you can call this method like this:
replace("PassyourString" , " " , "");
public static String replace(String s, String f, String r) {
if (s == null) {
return s;
}
if (f == null) {
return s;
}
if (r == null) {
r = "";
}
int index01 = s.indexOf(f);
while (index01 != -1) {
s = s.substring(0, index01) + r + s.substring(index01 + f.length());
index01 += r.length();
index01 = s.indexOf(f, index01);
}
return s;
}

Categories

Resources