I am a begining software engineer in college and have been stumped by a small problem. The assignment is to "encrypt" any text entered. All we have to do is make capitals lower case and vice versa, additionally we have to make a's z's, b's y's and so on.

//import java.util.Scanner;
//import java.util.Formatter;
import java.util.*;
public class Upper {


public static void main(String[] args) throws Exception {



int x;
String s;
char ch;


Formatter output = new Formatter ("CIA.txt");
Scanner input = new Scanner ( System.in );



System.out.println("Enter text ");
while (input.hasNext())
{
s = input.nextLine();
for (x=0; x <= s.length()-1;x++)
{
ch=s.charAt(x);
if ((ch >= 'a') && (ch <= 'z'))
ch=(char)(((int)ch)-((int)'a')+(int)'A');



output.format("%s",ch);
}
output.format("\n");
//System.out.println();
}
output.close();
}
// end of main method


}
// end of the class

Edited 3 Years Ago by Nick Evan: Fixed formatting

what are you doing this for?

(char)(((int)ch)

basicly, you have a char, which you transform into an integer primitive, just to transform it to a char again.

not only is this completely useless, but it makes your code quite annoying to read, since just one misplaced or forgotten ')' (or ( { } off course) will crash your code.

can you clean up your code a bit?

Yes, post cleaned-up properly indented code in CODE tags, and remember that char is an integral numeric type, so you can do arithmetic with chars directly. You don't need a lot of comments, but >0 would be a good idea; explain the overall intention behind each major section of code.

Edited 3 Years Ago by happygeek: fixed formatting

Create a "translation string".
substring() your input string, one character at a time.
Create your output string, based on your input string "translated" to your "translation string".

This article has been dead for over six months. Start a new discussion instead.