我正在用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.");
}
}发布于 2016-03-11 06:30:23
如果第二个命令行参数是整数
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.");
}
}如果它不是整数,那么它将抛出一个错误。
https://stackoverflow.com/questions/35928496
复制相似问题