需要帮助保存和继续用户输入

时间:2013-10-23 03:39:49

标签: java loops if-statement encryption

我正在尝试创建一个可以加密单词的单词游戏,并根据用户输入的内容将字符移动一定数量,解密该加密,并检查单词是否为回文。问题是我不知道如何保持输入,所以在我加密或检查它是否是回文后程序结束所以我无法解密已加密的内容。

例如 - 如果用户输入单词“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);
      }

   }
}

谢谢

2 个答案:

答案 0 :(得分: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"))

答案 1 :(得分:0)

有一个do-while循环

do{
   //your logic
}while(choice!=0);
相关问题