2013-10-23 30 views
0

我想創建一個文字遊戲,可以加密一個單詞,並通過用戶輸入的內容將字符移動一定數量,解密該加密,並檢查該單詞是否是迴文。問題是我不知道如何保持輸入,所以在我加密或檢查它是否是迴文記錄程序結束後,我無法解密已加密的內容。需要幫助保存和繼續用戶輸入

例如,如果用戶輸入單詞「hello」並選擇加密該單詞,則用3的鍵應顯示「khoor」。然後我想繼續解密「khoor」回到「你好」,但程序結束。

此外,當用戶輸入一個鍵號時,字符會移動比輸入數字多7個字符。

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-"); 
     String toUpperCase; 
     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 - 65); 
      int n = c+select; 
      n = n % 26; 
      if (n < 0) { 
       n = n + 26; 
      } 
      c = (char)(n + 65); 
     } 
     System.out.print(c); 
     } 
     } 
     else if(choice==2) 
    { 
    System.out.println("Insert a Key number"); 
    int select2= in.nextInt(); 


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

     } 
     if(key==0) 
     { 
     System.out.println("Word has not been encrypted yet."); 
     } 

} 



    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

把你的邏輯,從第一輸入開始do-while循環。然後在最後使用一個變量來決定何時退出。

String isExit = "N"; 
do{ 
    System.out.println("-Type any word-"); 
    String toUpperCase; 
    word = in.nextLine(); 
    System.out.println(Menu); 
. 
. 
. 
. 
System.out.println("-Exit? Y/N-"); 
    isExit = in.nextLine(); 

}while(!isExit.equals("Y")) 
0

有一個do-while循環

do{ 
    //your logic 
}while(choice!=0);