Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (498)
Games in Android Showcase (117)
games submitted by our members
Games in WIP (563)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Caesar Cypher problem  (Read 2265 times)
0 Members and 1 Guest are viewing this topic.
Offline Hauk

Junior Member




Guitar, Norse Mythology, java and women=life


« Posted 2005-11-29 23:28:48 »

Hey guys, me again

I'm trying to write a Caesar cypher program to help me learn and understand arrays, so I have to shift to the next letter from the letter in the message to create the cypher.

Here's what I have so far

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
public class CaesarCypher 
{
   static String encryptTheMessage(String message)
   {
      String newString = "";

      char alphabet [] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

      for(int i = 0; i < message.length(); i++)
      {
         char oldChar = message.charAt(i);
           
         newString = newString + alphabet[oldChar + 1];        
      }

      return newString;
   }

   public static void main(String [] args)
   {
      System.out.print("Enter a message to encrypt: ");

      String userMessage = Console.readString();

      String encryptedMessage = encryptTheMessage(userMessage);
     
      System.out.print("The encrypted message is: " + encryptedMessage);
   }
}


If you compile it, it gives you an out of bounds exception, but I don't know where I'm going wrong. I've written the problem out on paper and attempted the solution and just can't get it. So any ideas??

Thx guys

Hauk

I want to become a hermit and live in the harsh wastelands of Norway. I want to have a cloak made of bearskin and hunt the demons of the night.

I was born for a reason and am not about to lie down and die like the rest of you. Anybody with me?
Offline Vorax

Senior Member


Projects: 1


System shutting down in 5..4..3...


« Reply #1 - Posted 2005-11-29 23:49:36 »

Hmmm....this looks like homework...however....

The key to your problem is here:

char oldChar = message.charAt(i);

Remember that arrays access starts at 0 - check the value of oldChar and then walk through the rest of your program.

Offline blahblahblahh

JGO Coder


Medals: 1


http://t-machine.org


« Reply #2 - Posted 2005-11-29 23:51:21 »

Hey guys, me again

I'm trying to write a Caesar cypher program to help me learn and understand arrays, so I have to shift to the next letter from the letter in the message to create the cypher.

Here's what I have so far

1  
         newString = newString + alphabet[oldChar + 1];         


there's your bug. when oldChar is 26, you need to do alphabet[ 0 ].

your algorithm is wrong on paper - it should have said (although this isnt necessairly the most efficient way of implementing it)

newString += alphabet[  (oldChar+1) % 26 ];

because mod is the standard mathematical way of making it roll-around the ends.

ALSO, more useuflly algorithmically, this can accomodate a user-supplied ROT - e.g. ROT13 - with no code changes.

Although watch out for negative ROT from the user - I have vague memories that java happily returns negative numbers from % of negative numbers Sad.

malloc will be first against the wall when the revolution comes...
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline blahblahblahh

JGO Coder


Medals: 1


http://t-machine.org


« Reply #3 - Posted 2005-11-29 23:52:11 »

...but even that won't work because char converted to a number isn't simply 0 == 'a' etc, IIRC

malloc will be first against the wall when the revolution comes...
Offline Tzan

Junior Member





« Reply #4 - Posted 2005-11-30 00:04:51 »

...but even that won't work because char converted to a number isn't simply 0 == 'a' etc, IIRC

Correct, its the ASCII value.
Offline Jeff

JGO Coder




Got any cats?


« Reply #5 - Posted 2005-11-30 00:46:12 »

yup.

And again this sounds like homework.  And we generally don't do people's hoemwork here, but since you at elast started it.

You have an aditional problem that charAt(0 returns a char. And a char isn't ASCII, its unicode.

There are various solutions to this. The slowest but simplest would be (In psuedo code)

FOR EACH CHARACTER IN CHARACTERARRAY
   INDEX = 0
   DONE = FALSE
   WHILE NOT DONE
          IF ARRAY[INDEX] == CHARACTER
                 DONE=TRUE
          ELSE
                INDEX = INDEX +1
                IF INDEX >= ARRAYLENGTH
                       PRINT "ERROR CHARACTER "+CHARACTER+" NOT FOUND"
                       QUIT
                ENDIF
          ENDIF
   END WHILE
   INDEX = (INDEX+1)%ARRAYLENGTH
   OUTPUT = OUTPUT + CHARACTERARRAY[INDEX]
END FOR

This is psuedo code. Its not Java.  You will have to actually write the program yourself.
                 

Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Offline ryanm

Senior Member


Projects: 1
Exp: 15 years


Used to be bleb


« Reply #6 - Posted 2005-11-30 00:49:20 »

ooh ooh ooh! I have a suggestion too!

The String "+" concatenation operation is converted behind the scenes to use the StringBuilder class, so

1  
String s = "I like to con" + "catenate strings";

becomes something like
1  
2  
3  
StringBuilder sb = new StringBuilder( "I like to con" );
sb.append( "catenate strings" );
String s = sb.toString();


For a once-off concatenation, you don't need to worry about it, but using string = string + string in a loop will be a lot slower than it could be.

Anyhoo, the upshot is:
You should use a StringBuilder, and it's append() method, to build a string.
Offline Jeff

JGO Coder




Got any cats?


« Reply #7 - Posted 2005-11-30 01:04:14 »

True but probably not significant in this particular case  Grin

The looping search for the charcteris goign to be the primary CPU hog.

This could be improved with everything from hash table to a  precomputed translation array but, given his apprent level, I wanted to keep it basic Cool

(Actually you couls do it all in Unicode space IF you knew that the ordinal order of Unicode was the same as your translation order,or had a fixed translation from and to Unicdoe order,  but he said he wanted to do it with an array so I didn't mention that.)

Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Offline blahblahblahh

JGO Coder


Medals: 1


http://t-machine.org


« Reply #8 - Posted 2005-11-30 01:26:59 »

ooh ooh ooh! I have a suggestion too!

For a once-off concatenation, you don't need to worry about it, but using string = string + string in a loop will be a lot slower than it could be.

Anyhoo, the upshot is:
You should use a StringBuilder, and it's append() method, to build a string.

Huh? Isn't that optimized away as it should be, by the compiler, as of about java 1.3?

malloc will be first against the wall when the revolution comes...
Offline rdcarvallo

Senior Member


Projects: 5
Exp: 15 years


2D Java games forever!


« Reply #9 - Posted 2005-11-30 02:28:17 »

Instead of looking for the oldChar index in the array, since the alphabet is ordered, you can do:
1  
2  
int  oldChar = message.charAt(i) - 'a'//This give you the index for the alphabet array
newString = newString + alphabet[(oldChar + 1)%26]; //The case 26 + 1 -> 0


   Rafael..
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ryanm

Senior Member


Projects: 1
Exp: 15 years


Used to be bleb


« Reply #10 - Posted 2005-11-30 09:40:40 »

ooh ooh ooh! I have a suggestion too!

For a once-off concatenation, you don't need to worry about it, but using string = string + string in a loop will be a lot slower than it could be.

Anyhoo, the upshot is:
You should use a StringBuilder, and it's append() method, to build a string.

Huh? Isn't that optimized away as it should be, by the compiler, as of about java 1.3?

I seem to remember making huge speed ups switching to StringBuilder (or StringBuffers as there was then) on 1.4, but it may be because the way I was building the string was sufficiently obscured that the compiler didn't catch it.
In any case, if you're building a string, it seems sensible to use a StringBuilder  Grin
Offline pepijnve

Junior Member




Java games rock!


« Reply #11 - Posted 2005-11-30 10:44:39 »

ooh ooh ooh! I have a suggestion too!

For a once-off concatenation, you don't need to worry about it, but using string = string + string in a loop will be a lot slower than it could be.

Anyhoo, the upshot is:
You should use a StringBuilder, and it's append() method, to build a string.

Huh? Isn't that optimized away as it should be, by the compiler, as of about java 1.3?

Nope. The compiler optimizes simple cases, but not across loops. As an example the following code
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
private static String append1() {
    String a = "a" + "b" + "c" + "d";

    return a;
}

private static String append2() {
    String[] subStrings = new String[] {
        "a",
        "b",
        "c",
        "d"
    };

    String a = "";
    for (int i = 0; i < subStrings.length; i++) {
        a += subStrings[i];
    }

    return a;
}

Results in the following byte code (using the 1.4.2_03 compiler)
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
private static java.lang.String append1();
  Code:
   0:   ldc     #4; //String abcd
  2:   astore_0
   3:   aload_0
   4:   areturn

private static java.lang.String append2();
  Code:
   0:   iconst_4
   1:   anewarray       #5; //class java/lang/String
  4:   dup
   5:   iconst_0
   6:   ldc     #6; //String a
  8:   aastore
   9:   dup
   10:  iconst_1
   11:  ldc     #7; //String b
  13:  aastore
   14:  dup
   15:  iconst_2
   16:  ldc     #8; //String c
  18:  aastore
   19:  dup
   20:  iconst_3
   21:  ldc     #9; //String d
  23:  aastore
   24:  astore_0
   25:  ldc     #10; //String
  27:  astore_1
   28:  iconst_0
   29:  istore_2
   30:  iload_2
   31:  aload_0
   32:  arraylength
   33:  if_icmpge       63
   36:  new     #11; //class java/lang/StringBuffer
  39:  dup
   40:  invokespecial   #12; //Method java/lang/StringBuffer."<init>":()V
  43:  aload_1
   44:  invokevirtual   #13; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer;
  47:  aload_0
   48:  iload_2
   49:  aaload
   50:  invokevirtual   #13; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer;
  53:  invokevirtual   #14; //Method java/lang/StringBuffer.toString:()Ljava/lang/String;
  56:  astore_1
   57:  iinc    2, 1
   60:  goto    30
   63:  aload_1
   64:  areturn
}

As you can see the StringBuffer optimization is done inside the loop, but not across the entire loop.
Offline Tzan

Junior Member





« Reply #12 - Posted 2005-11-30 16:39:51 »

And a char isn't ASCII, its unicode.


Yup I know, but the decimal value is identical and the back of my Java 2 book doesnt have a Unicode table, it has an ASCII table. So I figured his might be the same way.

My initial impulse was to explain it all, then I held back with just a small but incomplete comment Smiley
Offline Jeff

JGO Coder




Got any cats?


« Reply #13 - Posted 2005-11-30 23:43:42 »

Fair enough, thopugh he'll get REALLY out of range numerbs if he encounters any non-US characters  Grin

Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Grunnt (13 views)
2014-09-23 14:38:19

radar3301 (14 views)
2014-09-21 23:33:17

BurntPizza (31 views)
2014-09-21 02:42:18

BurntPizza (22 views)
2014-09-21 01:30:30

moogie (20 views)
2014-09-21 00:26:15

UprightPath (29 views)
2014-09-20 20:14:06

BurntPizza (33 views)
2014-09-19 03:14:18

Dwinin (48 views)
2014-09-12 09:08:26

Norakomi (75 views)
2014-09-10 13:57:51

TehJavaDev (105 views)
2014-09-10 06:39:09
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!