我正在研究java中的ceasar密码加密程序。您要求用户输入将加密文本的文本和密钥的位置。 如果他们不输入数字,它将输入一个随机数。尚未尝试解密文本。 同样得到错误在第29行,cmd一直在说二进制运算符的坏操作数类型。
import java.util.Scanner;
import java.util.Random;
public class A {
public static void main(String[] args) {
System.out.println("This program encrypts text you enter using the Caesar Cipher.\n");
Scanner sc = new Scanner(System.in);
String text;
String line;
String choice;
String shift;
char[] alphabet = {'A', 'B','C','D','E', 'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int key;
int caeserVal;
int sum;
String doAgain;
do {
System.out.println("Enter a line text to encrypt: ");
line = sc.nextLine();
System.out.print("Enter the key between -25 and 25. Enter 0 to have it generate a random key: ");
key = sc.nextInt();
sum = 0;
char[] plaintext = args[0].toCharArray();
shift = args[1];
for(int i = 0; i < plaintext.length; i++) {
for(int j = 0; j < alphabet.length; j++) {
if(alphabet[j] == plaintext[i]) {
plaintext[i] = alphabet[(j + shift) % alphabet.length];
}
}
}
String ciphertext = new String(plaintext);
System.out.println(ciphertext);
caeserVal = sum + key;
System.out.printf("The text encrypted with key %d is %s.\n", key,caeserVal);
System.out.print("Try again(y or n)? ");
choice = sc.nextLine().toUpperCase();
}while(choice.equals("Y"));
System.out.println("Thank you for using this program.");
}
}
答案 0 :(得分:0)
如果第二个命令行参数是整数
import java.util.Scanner;
import java.util.Random;
public class A {
public static void main(String[] args) {
System.out.println("This program encrypts text you enter using the Caesar Cipher.\n");
Scanner sc = new Scanner(System.in);
String text;
String line;
String choice;
String shift;
char[] alphabet = {'A', 'B','C','D','E', 'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int key;
int caeserVal;
int sum;
String doAgain;
do {
System.out.println("Enter a line text to encrypt: ");
line = sc.nextLine();
System.out.print("Enter the key between -25 and 25. Enter 0 to have it generate a random key: ");
key = sc.nextInt();
sum = 0;
char[] plaintext = args[0].toCharArray();
shift = args[1];
for(int i = 0; i < plaintext.length; i++) {
for(int j = 0; j < alphabet.length; j++) {
if(alphabet[j] == plaintext[i]) {
plaintext[i] = alphabet[((j + Integer.parseInt(shift)) % alphabet.length)];
}
}
}
String ciphertext = new String(plaintext);
System.out.println(ciphertext);
caeserVal = sum + key;
System.out.printf("The text encrypted with key %d is %s.\n", key,caeserVal);
System.out.print("Try again(y or n)? ");
choice = sc.nextLine().toUpperCase();
}while(choice.equals("Y"));
System.out.println("Thank you for using this program.");
}
}
如果它不是整数,则会引发错误。