1

I am not sure but I think my problem is that my function doesn't compare the char´s right. Am I using the Switch also right?

my input x is a String and when x = "aaaaa" it returns "aaaaa" instead of "zzzzz".

String c = ""; for (int i = 0; i < x.length(); i++) { char getChar = x.charAt(i); switch (getChar) { case 1: (getChar) = 'a'; c += "z"; break; case 2: (getChar) = 'b'; c += "y"; break; case 3: (getChar) = 'c'; c += "x"; break; case 4: (getChar) = 'd'; c += "w"; break; case 5: (getChar) = 'e'; c += "v"; break; case 6: (getChar) = 'f'; c += "u"; break; case 7: (getChar) = 'g'; c += "t"; break; case 8: (getChar) = 'h'; c += "s"; break; case 9: (getChar) = 'i'; c += "r"; break; case 10:(getChar) = 'j'; c += "q"; break; case 11:(getChar) = 'k'; c+= "p"; break; case 12:(getChar) = 'l'; c += "o"; break; case 13:(getChar) = 'm'; c += "n"; break; default : c += x.charAt(i); } } System.out.println(c); } 
3
  • 3
    You should use case 'a'.. instead. The decimal value of 'a' is not 0. Also use a StringBuilder instead of +. Commented Jun 23, 2014 at 14:18
  • @MarounMaroun why is it better to use StringBuilder instead of what i do? Commented Jun 23, 2014 at 14:51
  • See this link for details. Commented Jun 23, 2014 at 14:54

2 Answers 2

5
switch (getChar)//<--You are passing charcter in switch case //but checking for 1,2 int as case 1,2... 

What you need to change is your case

as in switch you will be passing characters like a,b,c...

switch(getchar) { case 'a': //yourwork break; //do this for all letters } 

NOTE

Moreover for concacting String you should use StringBuilder (As Maroun Maroun) has already suggested and use stringBuilder.append('char') method to add your character to String builder directly no need to use String (i.e "a","b" etc.).

Sign up to request clarification or add additional context in comments.

1 Comment

why is it better to use StringBuilder instead of what i do?
0

A switch statement is not the best option if all cases are treated in almost exactly the same way and can be easily converted into a single calculation. You can replace the entire switch statement with this if/else block:

if (getChar >= 'a' && getChar <= 'm') { char newChar = (char) ('z' - (getChar - 'a')); c += newChar; } else { c += getChar; } 

NOTE: @TAsk and @MarounMaroun are right in advising you to use StringBuilder to build up your result.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.