2013-10-22 135 views
1

所以我有一個文字遊戲項目,我必須加密一些字符。我處於卡住的地步,當我運行它並鍵入1進行加密時,它不會移動那麼多字母。它只是再次打印工作。我想知道我能做些什麼來修復它,如果我說「你好」,它會打印1個字符並說「ifmmp」謝謝!我在這裏加密錯了什麼?

import java.util.Scanner; 

public class WordPlayTester{ 

    public static void main(String [] args){ 

    String word, reverse=""; 
    String original; 
    int key= 0; 
    String Menu= "1-Encrypt \n2-Decrypt \n3-Is Palindrome \n0-Quit \n-Select an option-"; 

    Scanner in = new Scanner(System.in); 
    System.out.println("-Type any word-"); 
      word = in.nextLine(); 
    System.out.println(Menu); 

     int choice=in.nextInt(); 
     if(choice==1) 
     { 
     System.out.println("Insert a Key number"); 
     int select= in.nextInt(); 


      for (int i=0; i < word.length(); i++) { 
      char c = word.charAt(i); 
      if (c >= 'A' && c <= 'Z') { 
       c = (char)(c - 64); 
       int n = c+1; 
       n = n % 26; 
       if (n < 0) { 
        n = n + 26; 
       } 
       c = (char)(n + 65); 
      } 
      System.out.println(c); 
      } 
      } 


     else if(choice==3) 
     { 
     int length = word.length(); 
      for (int i = length - 1 ; i >= 0 ; i--) 
      reverse = reverse + word.charAt(i); 
      if (word.equals(reverse)) 
      System.out.println("Your word is a palindrome."); 
      else 
      System.out.println("Your word is not a palindrome."); 


      } 
      else if(choice==0) 
      { 
      System.exit(0); 
      } 

     else 
      { 
      System.out.println(Menu); 
      } 


    } 
} 
+1

你減去64;你加65.這是正確的嗎? –

+0

我相信這是我認爲是正確的,是不是錯誤? – KayterNater

+0

那麼宗正禮,你認爲我應該讓他們小寫而不是上面,它應該運行一個字符的字? – KayterNater

回答

0

這裏的一些修改後,簡化代碼:

import java.util.Scanner; 

public class WordPlayTester { 

    public static void main(String [] args) { 

    String word; 
    int key= 0; 

    Scanner in = new Scanner(System.in); 
    System.out.println("-Type any word-"); 
    word = in.nextLine(); 

    System.out.println("Insert a Key number"); 
    int select = in.nextInt(); 

    for (int i=0; i < word.length(); i++) { 
     char c = word.charAt(i); 
     if (c >= 'A' && c <= 'Z') { 
     c = (char)(c - (int)'A'); 
     int n = c+select; 
     n = n % 26; 
     if (n < 0) { 
      n = n + 26; 
     } 
     c = (char)(n + (int)'A'); 
     } 
     System.out.print(c); 
    } 
    System.out.print('\n'); 
    } 
} 

給定輸入拜占庭和鍵1,則輸出CZABOUJVN;給定密鑰2,它輸出DABCPVKWO;給定鍵25,它輸出AXYZMSHTL;給定鍵26,它輸出BYZANTIUM。

+0

謝謝,但是當你輸入小寫字母它不起作用時,有什麼能解決這個問題嗎? – KayterNater

+0

我採取了你所做的,只是試圖映射大寫ASCII字母,並使其正確工作。很明顯,你可以爲小寫字母創建一個平行的代碼塊,但它非常難看。你也可以簡化你的代碼。至少,我希望創建一個函數來完成兩次轉換(低,高,select和c作爲參數)。我期望Java與C isupper/islower函數類似;使用它們。當然,像這樣的凱撒密碼並不是安全的縮影。一種變體稱爲ROT13,對應於13的關鍵數字。 –

相關問題