Java Help?

FreakingHell

Poster Extraordinaire
Joined
Sep 1, 2008
Messages
2,181
Well, I am working on a project for java class. What we are supposed to do is make a program, that when given a string and a number, will convert said string to ASCII, add the given number to each of the ASCII numbers, and then convert it back to English. If a capital letter is given, it must return a capital letter. It must be able to do whole sentences. It must wrap around(ex. if the original letter was x, and the number was 5, it should end up being c). With the code I currently have, it doesn't take into effect capitals, or wrapping around. All I am trying to get it to do at this point is to get it to return a word. For some unknown reason, it won't return more than the first letter converted. I have no idea why. Help? Code below. Thanks.

import java.util.Scanner;

public class ASCIICoder
{

public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);

int z = 0;
while(z==0)
{
System.out.println("Which would you like to do?" +
"\n1. Code a sentence" +
"\n2. Decode a sentence" +
"\n3. Quit.");
int choice = keyboard.nextInt();

switch (choice)
{
case 1:

System.out.println("What is the string?");
String sentence = keyboard.next();
System.out.println("What is the ASCII number?");
keyboard.nextLine();
int num = keyboard.nextInt();
System.out.println(oneLetter(sentence, num));

;break;

case 2:


;break;

case 3:

System.out.println("Good bye.");
z++;
;break;


}


}



}

public static String coder(String a, int num)
{
String temp = "";

for(int i = 0; i < a.length();i++)
{
String oneLetter = a.charAt(i)+"";
char letter = oneLetter(oneLetter, num);
temp += letter;

}
return temp;
}

public static char oneLetter(String a, int num)
{
int temp = (int)a.charAt(0);
temp += num;
char b = (char)temp;
return b;
}

}
 
In your case statement (case 1), you make a call to oneLetter() which returns a char. You then print that char. I think you want to be calling coder(), instead of oneLetter().
 
If I'm understanding the problem correctly, you essentially want to build a simple encryption/decryption program that will encrypt a string with a key and also be able to get the original string back with the same key - is that right?

If so, there are probably a lot of ways to do this, but this is the way I would go about it:

At the core of the program you should have two main functions: encrypt and decrypt. The purpose of these functions would be to accept a string and a key and return a new encrypted/decrypted string.

Here is what an encryption function could like in Java (I'll explain it line-by-line below)

Code:
public String encrypt(String inputString, int key)
{
     String encryptedString = "";

     for(int i=0; i<inputString.length(); i++)
     {
          encryptedString += (char)(((int)inputString.charAt(i) + key) % 256);
     }

     return encryptedString;
}

So here, the basic idea is that we are going through each character of the inputString, altering it with the key and then adding it to the encryptedString.

The first line (after the function header) declares the variable that we will use to store the final encrypted string and gives it an initial value of null.

The next section is the main for-loop. This loop goes through each character of inputString and keeps track of the current index with the variable i. Inside the loop is where the real work begins.

Code:
encryptedString += (char)(((int)inputString.charAt(i) + key) % 256);

We'll sort've work this one from the inside-out:

1) We get the character at index i of inputString
  • inputString.charAt(i)
2) Cast that character to an integer so we can get the numerical ASCII value (between 0 and 255)
  • (int)inputString.charAt(i)
3) Add the value of the key to it
  • (int)inputString.charAt(i) + key
4) Then take that result and use the % operator - otherwise known as the MOD function - to force the final value to be between 0 and 255. (I can explain this process further if you would like)
  • ((int)inputString.charAt(i) + key) % 256
5) Finally, we cast that result back to a character
  • (char)(((int)inputString.charAt(i) + key) % 256)

After we convert it back into a character, we add that value to the encryptedString and continue the loop until all the characters have been encrypted. After the entire string as been converted, it will return the encrypted string so you can use it in your main program (print it out, etc...).

Again, if you're having any troubles with the any aspect of the code, just let me know.

Also, if you know and understand how this code works then writing the decrypt function will be incredibly easy.

I hope that this helps!

Tyler
 
Last edited:
In your case statement (case 1), you make a call to oneLetter() which returns a char. You then print that char. I think you want to be calling coder(), instead of oneLetter().

Yes, you are correct. That was the error. Knew it was something simple, but couldn't find it.

@ Phoenix, thanks, that helps a bunch. However, the mod part is unnecessary as it is only supposed to convert capital and lowercase letters, and leave everything else alone. Which brings me to my next question...I'm having trouble making it not try to convert punctuation and spaces... What would be the simplest way to do that? The way I'm trying(which isn't working) is like 22 lines long...yeah. Because I need to be able to convert a whole sentence, not just a word. Therefore I will have to find the index of a space and then convert it one word at a time -- correct?
 
The below code should make it skip over spaces -- correct? Now I just need to make it wrap around and not convert punctuation.

public String code(String input, int key)
{
String coded = "";

for(int i=0; i<input.length(); i++)
{

if(input.charAt(i) != ' ')
{
coded += (char)((int)input.charAt(i) + key);
}

}

return coded;
}
 
.I'm having trouble making it not try to convert punctuation and spaces... What would be the simplest way to do that?

As you traverse the string character by character, you could encode the current character only if it matches a letter in an alphabet. See java.util.regex.
 
I agree with BaHAmuT. Using regular expressions is definitely the simplest way to go.

Sorry about the confusion - If I can be any more help, just let me know!

Tyler
 
Ok. I am unfamiliar with using the regex package. Would the below code work correctly? The red line is the one I'm wondering about.

import java.util.regex.*;

public String code(String input, int key)
{
String coded = "";

for(int i=0; i<input.length(); i++)
{


String k = input.charAt(i);
if(k.matches("[a-zA-Z]"))
{
coded += (char)((int)input.charAt(i) + key);
}

}

return coded;
}
 
Last edited:
Ok. I am unfamiliar with using the regex package. Would the below code work correctly? The red line is the one I'm wondering about.

That won't even compile. String k = input.charAt(i); returns a char. You can't coerce a char into a String =).
 
Actually, that line will work with a little trick.

Instead of:
Code:
String k = input.charAt(i);

Put:
Code:
String k = "" + input.charAt(i);

That will concatenate it with an empty string so it will be recognized as a string of one character.

As for the rest, when I ran your code it did work - however, when the character is not an upper or lowercase letter, it get's ignored and not added to the final string that is being returned. Is this what you were wanting?

Tyler
 
Oh yeah, I meant to add that part to make it a string...forgot. And yeah, that isn't what i wanted. I'm supposed to have it return any punctuation/spacing just like it was...which I think is easy enough? Just add an else statement and add string k to coded(what's being returned).

Another question, can I have an if statement inside an if statement, and an else statement on the original(outer) if ? Pretty sure I can, but not certain.
 
Last edited:
Another question, can I have an if statement inside an if statement, and an else statement on the original(outer) if ? Pretty sure I can, but not certain.

Yep.

Code:
if (expression1) {
  if (expression2) {
  }
}
else {
  // executed when expression1 is false
}
 
Back
Top