2015-11-02 54 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

相關問題