我的任务是将字符串转换为其各自的unicode整数,根据所需的加密(左或右以及多少空格)进行移位。我能够很好地理解这部分。但后来我需要输入转换后的unicode字符串并将其转换回输入的原始字符串。这是我的代码。我无法弄清楚如何将unicode字符串转换回原始字符串。 **注意 - 我只允许使用输入和字符串。
import java.util.Scanner;
import java.lang.String;
import java.lang.Character;
public class CSCD210_HW2
{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
String str, str1 = "";
String encrypt, decrypt = "";
int i = 0;
int i1 = (int)0;
System.out.printf("Please enter a string:");
str = input.nextLine();
System.out.printf("\nPlease enter encryption format - \'left\' or \'right\'" +
" \"space\" number of spaces:");
encrypt = input.nextLine();
int length = str.length();
String spaces = encrypt.substring(encrypt.lastIndexOf(' ') + 1);
Integer x = Integer.valueOf(spaces);
//encrypt
if (encrypt.startsWith("l")){
while (i < length){
int uni = (int)(str.charAt(i++));
char uni1 = (char)uni;
int result = uni + x;
System.out.print(result + " ");}}
else if (encrypt.startsWith("r")){
while (i < length){
int uni = (int)(str.charAt(i++));
char uni1 = (char)uni;
int result = uni - x;
System.out.print(result + " ");}}
//decrypt
System.out.printf("\nPlease enter encrypted string:");
str1 = input.nextLine();
System.out.printf("\n\'left\' or \'right\' \"space\" number of spaces:");
decrypt = input.nextLine();
int length1 = str1.length();
String spaces1 = decrypt.substring(decrypt.lastIndexOf(' ') + 1);
Integer y = Integer.valueOf(spaces1);
if (decrypt.startsWith("l")){
while (i < length1){
char word = (char)(str1.charAt(i++));
int result = word + y;
System.out.print(result);}}
else if (decrypt.startsWith("r")){
while (i < length1){
char word = (char)(str1.charAt(i++));
int result = word - y;
System.out.print(result);}}
}
}
答案 0 :(得分:0)
您的第二部分没有意义,因为您的加密值基本上是单个字符的3位数。因此,您需要一种方法将3个数字转换回1个字符,而不是每个数字创建一个字符。
将其替换为第二部分:
// split the input line containing the encrypted values into single tokens
// each token represents the numerical values of a single character
String[] tokens = str1.split("\\s");
// reserve some space for the characters
// char[] chars = new char[tokens.length];
String chars = "";
// keep track of the position
// int pos = 0;
for (String token : tokens)
{
if (decrypt.startsWith("l"))
{
// convert the string containing the number to integer
Integer val = Integer.parseInt(token);
// convert the integer back to char and apply the transformation
// chars[pos++] = ((char)(val.intValue()+y));
chars += ((char)(val.intValue()+y));
}
else
{
// convert the string containing the number to integer
Integer val = Integer.parseInt(token);
// convert the integer back to char and apply the transformation
// chars[pos++] = ((char)(val.intValue()-y));
chars += ((char)(val.intValue()-y));
}
}
// check if everything worked as expected
System.out.println(chars);
// System.out.println(new String(chars));
@Edit: 更新了OP的需求