无法将字符串转换为另一种方法

时间:2015-11-02 20:50:15

标签: java string encryption methods variable-assignment

我在完成这项任务时遇到了麻烦。提示是让用户输入要编码的消息。编码将接收消息并根据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;
    }
}

2 个答案:

答案 0 :(得分:0)

嘿,我发现它必须对Line做点什么。

int choice = input.nextInt();

我不知道为什么这不起作用,但我建议你可以使用

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

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

答案 1 :(得分:0)

所以我的兄弟帮助了我并想出我需要在选择1&amp;中开辟一个新的扫描仪2然后它让用户输入一个字符串并完成剩下的代码。