2015-11-02 49 views
0

我在分配时遇到问题。提示是让用户输入要编码的消息。根据ASCII表格,编码将消息并将每个字符向右移动4个空格。我认为我的加密和解密方法是正确的(?),但我无法分辨,因为我无法弄清楚如何获取输入到方法中的字符串。将字符串转换为其他方法时遇到问题

import java.util.Scanner; 

public class EncryptDecrypt { 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Welcome to my encrypting/decrypting program"); 
     System.out.println("_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ "); 
     System.out.println("(1) Encrypt a message."); 
     System.out.println("(2) Decrypt an encrypted message."); 
     System.out.println("(3) Exit."); 
     System.out.print("Your choice? "); 
     int choice = input.nextInt(); 
     if (choice != 3) { 
      if (choice == 1) { 
       System.out.println("Please enter a message to be encrypted: "); 
       String message = input.nextLine(); 
       System.out 
         .println("The encrypted string is " + encrypt(message)); 

      } 
      else { 
       System.out.println("Please enter a string to be decrypted: "); 
       String encrypted = input.nextLine(); 
       System.out.println(
         "The decrypted string is " + decrypt(encrypted)); 
      } 

     } else { 
      System.out.println("The program has been exited."); 
     } 
    } 

    public static String encrypt(String message) { 
     String encrypted = " "; 
     for (int i = 0; i < message.length(); i++) { 
      encrypted += (char) (message.charAt(i) + 4); 
     } 
     return encrypted; 

    } 

    public static String decrypt(String encrypted) { 
     String unencrypted = " "; 
     for (int i = 0; i < encrypted.length(); i++) { 
      unencrypted += (char) (encrypted.charAt(i) - 4); 

     } 
     return unencrypted; 
    } 
} 
+0

用户输入字符串后,您看到什么信息? – AbtPst

+0

它永远不会达到这一点。当我运行该程序并输入一个选项(1,2或3)时,它将进入该选项并打印出此...“欢迎来到我的加密/解密程序 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ (1)加密的消息 (2)解密一加密的消息 (3)退出 你选择1 请输入要被加密的消息:。? 加密的字符串是 构建成功(总时间:1秒) –

回答

0

嘿,我发现它必须做一些线。

int choice = input.nextInt(); 

我不知道为什么还是不行,不过我建议你可以使用

int choice = Integer.parseInt(input.nextInt()); 

代替。这确实有效,但遗憾的是我不知道为什么。

+0

感谢您的回复,但我认为它与我的if语句有关。当我运行该程序并输入1,2或3的选择时。该选择只运行语句并结束程序而不让用户输入一个字符串 –

+0

不,它不是if语句如果你设置了直接选择y没有来自nextInt的输入,它会正确运行,所以我确定它与nextInt方法有关。 – CodeX

0

所以,我的兄弟帮助我,发现我需要打开一个新的扫描仪在选择1 & 2,然后它让用户输入一个字符串,并通过其余的代码。

+1

因此,您没有阅读重复问题(请参阅您的问题的第一条评论)? – Tom

相关问题