DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. Registered User
Join Date
Mar 2010
Posts
2

## ASCII Encoding

Hi,

So I'm new to this whole Java thing. I have to write a program that finds the ASCII encoding value for characters through type conversion, interchanging between characters and integers, visa-versa. The program has to bring the larger number values back into range at the beginning of the alphabet (ie: A+3 goes to D, B+3 goes to E). I've gotten this far, which isnt much, but have some instructions to follow and have gotten stuck at the modulus step. Any help would be greatly appreciated. These are the given instructions:

1. Set a constant equal to the amount to shift each character (make equal to 13 instead of 3)
2. For each position in the string:
- get the character at that position
- find the ASCII value
- If the ASCII value is between 65 & 90
*subtract 65 from the ASCII value to get value in the range of 0-25
*add the shift constant to ASCII value (range 13-38)
*use modulus operator and 26 to bring value back in 0-25 range
*add 65 back to get new value back in the A-Z range (65-90)
*convert the number back to a character
*end If
*add the character to the output string
3. End for

This is my code:
Code:
```package edu.uwec.cs.jimeneam.lab4;
import javax.swing.JOptionPane;
public class StringMethods {

/**
* @param args
*/
public static void main(String[] args) {

//Variables
int StopValue = 0;
int shiftConstant = 13;

//User input
String inputValueString = JOptionPane.showInputDialog(null,"Enter the message you wish to convert. Otherwise, enter " + StopValue + " to exit the program.");

//Conversion & Output
for ( int i = 0; i < inputValueString.length(); ++i ){
char c = inputValueString.charAt(i);
int j = ((int) c - 65 + shiftConstant);
JOptionPane.showMessageDialog(null, "The ASCII of "+ c +" is: " + j);
}
}
}```
Last edited by Hack; 03-15-2010 at 01:17 PM. Reason: Added Code Tags

2. Registered User
Join Date
May 2004
Posts
40

## Modulus operator

Do you understand what the modulus operator does? It is used to get the remainder for integer division. For example, 26 % 5 = 1 (26 / 5 = 5 r 1). So what your assignment is asking you to do is use mod 26 on your result to bring it back into the desired range. You can see a code example of mod here.

Essentially, you're being asked to create a new value from your variable j mod 26.

Two other things:
1. Please use code tags when posting code. It makes it much more readable.
2. You should use more meaningful names for your variables. Names like c, j, etc. only serve to confuse you later on.

Good luck and post again if you have more questions.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise