Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2012
    Posts
    1
    Rep Power
    0

    Default Question regarding type casting

    Before I start, I've searched through previous examples with sample code but most if not all used if/else statements, which I am forbidden from using in this assignment. I know it's a common program but I tried :(

    Anyway, I have a string of letters that I'm supposed to encode with a Caesar cipher. If you're not already familiar with the subject, all it does is take a message and shift all its letters down the alphabet by a set number of letters.

    I'm stuck at the rotational/encryption part of the program. In my head I figured I'd convert each letter in the string "message" to its respective ASCII value, add the encryption key (how many letters to shift down) to that value, and then cast it back to a character. I'm ignoring the possibility of wraparound until later.

    Java Code:
    for (int i = 0; i < message.length(); i++) {
    			int asciiValue = (int) message.charAt(i);
    			asciiValue += key;
    			asciiValue = (char) asciiValue;
    			System.out.print(asciiValue);
    }
    The output using that gives me the ASCII value of the letter, not the letter itself. So, using a key of 4 and inputting 'JAVA' gives me 78699069 instead of 'NEZE'.

    How do I convert the value to a character? I know the general form is char character = (char)ascii;, but I don't know where to go from there. I also know that there are multitudes of easier methods to do this program out there... but the only conditional statement I can use is a for loop. Thanks!
    Last edited by flyingdeutschman; 10-03-2012 at 04:02 AM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,001
    Rep Power
    20

    Default Re: Question regarding type casting

    Don't convert to int.
    Just add the key to the char.
    Java Code:
    char a = message.charAt(i);
    a += key;
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. type casting
    By saidinu in forum New To Java
    Replies: 1
    Last Post: 10-21-2011, 01:09 PM
  2. Type Casting
    By Shaheen Mohamed in forum New To Java
    Replies: 6
    Last Post: 08-17-2010, 07:56 PM
  3. help with type casting.
    By ramsrocker in forum Java Applets
    Replies: 15
    Last Post: 02-26-2009, 11:28 PM
  4. type casting
    By alvations in forum New To Java
    Replies: 1
    Last Post: 10-13-2008, 07:07 PM
  5. Type Casting Help
    By rhm54 in forum New To Java
    Replies: 2
    Last Post: 02-07-2008, 12:06 PM

Posting Permissions

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