首页 > 解决方案 > 如何在密码程序中包含空格?

问题描述

该代码询问您是否要对消息进行编码或解码,然后它会询问该消息。它将通过以下参考工作:“abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;:'”[]{}=+-_()*&^%$#@!~`0123456789"

"kngcadsxbvfhjtiumylzqropweKNGCADSXBVFHJTIUMYLZQROPWE,./<>?;:'"[]{}=+-_()*&^%$#@!~`0123456789"

因此,例如,如果您尝试对字母“a”进行编码,它将输出字母“k”。

我的问题是我在输入消息时不能包含任何空格。

这是我的代码:

import java.util.Scanner;

public class SecretMessage {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        do {
            System.out.println("Enter 1 to encode, 2 to decode, 3 to quit:");
            int start = input.nextInt();

            if (start == 3){
                break;
            }

            System.out.println("Type your message:");
            String test = input.next();
            String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;:’”[]{}=+-_()*&^%$#@!~`0123456789 ";
            String enc = "kngcadsxbvfhjtiumylzqropweKNGCADSXBVFHJTIUMYLZQROPWE,./<>?;:’”[]{}=+-_()*&^%$#@!~`0123456789 ";

            char[] array = test.toCharArray();
            char[] decoded = letters.toCharArray();
            char[] encoded = enc.toCharArray();
            int[] position = new int[array.length];
            char[] end = new char[array.length];

            if (start == 1){
                for (int i = 0; i < test.length(); i++){
                    for (int j = 0; j < decoded.length; j++){
                        if (array[i] == decoded[j]){
                            position[i] = j;
                        }
                    }
                }

                for (int f = 0; f < test.length(); f++){
                    end[f] = encoded[position[f]];
                }

                for (int x = 0; x < test.length(); x++){
                    System.out.print(end[x]);
                }
                System.out.println(" ");
            } else {
                for (int i = 0; i < test.length(); i++){
                    for (int j = 0; j < encoded.length; j++){
                        if (array[i] == encoded[j]){
                            position[i] = j;
                        }
                    }
                }

                for (int f = 0; f < test.length(); f++){
                    end[f] = decoded[position[f]];
                }

                String output = new String(end);
                System.out.println(output);
            }
            System.out.println(" ");
        } while (1 ==1);

    }
}

标签: java

解决方案


推荐阅读