desert564 0 Light Poster

I have this Caesar Cipher program, but it's decoding function is buggy. When you try to decode ABCDEFGHIJKLMNOPQRSTUVWXYZ it should return NOPQRSTUVWXYZABCDEFGHIJKLM but instead it returns DEFGHIJKLMNOPABCDEFGHIJKLM.
I believe the code is in lines 36, 37, 43, & 44 and occurs when c becomes negative but I don't know how to fix this problem because I'm still new at this. Any thoughts?
view sourceprint?01 import java.util.Scanner;

02 public class Cipher {

03 public static void main(String[] args) {

04 Scanner input = new Scanner(System.in);

05 String text = "";

06 int encode = 0;

07 int key = 13;

08 int i = 0;

09 System.out.println("Type in the plaintext.");

10 text = input.nextLine();

11 //System.out.println(text);

12 if(encode == 1){//This is for encoding.

13 for (i = 0; i < text.length(); i++) {

14 char c = text.charAt(i);

15 if( c >= 'a' && c <= 'z'){

16 c -= 97;

17 c += key;

18 c %= 26;

19 c += 97;

20 }

21 else if( c >= 'A' && c <= 'Z'){

22 c -= 65;

23 c += key;

24 c %= 26;

25 c += 65;

26 }

27 System.out.print(c);

28 }

29 }

30 if(encode == 0){//This is for decoding

31 //The decoding process is currently buggy.

32 for (i = 0; i < text.length(); i++) {

33 char c = text.charAt(i);

34 if( c >= 'a' && c <= 'z'){

35 c -= 97;

36 c -= 26 - key;

37 c %= 26; //This line is where the decoding goes wrong

38 c += 97;

39

40 }

41 else if( c >= 'A' && c <= 'Z'){

42 c -= 65;

43 c -= 26 - key;

44 c %= 26; //This line is where the decoding goes wrong

45 c += 65;

46 }

47 System.out.print(c);

48 }

49 }

50 }

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.