Я создаю программу для шифра Цезаря, которая сдвигает буквы в слове один раз, когда я нажимаю клавишу ввода, и предлагает пользователю снова сдвинуть или выйти.
Он работает, пока я не доберусь до 23 смен, затем по какой-то причине он начинает использовать небуквенные символы, и я не уверен, почему это происходит.
Какие-либо предложения? Вот код:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Cipher {
public static void main(String[] args) {
// encrypted text
String ciphertext;
// input from keyboard
Scanner keyboard = new Scanner(System.in);
if (args.length > 0) {
ciphertext = "";
try {
Scanner inputFile = new Scanner(new File(args[0]));
while (inputFile.hasNext())
ciphertext += inputFile.nextLine();
} catch (IOException ioe) {
System.out.println("File not found: " + args[0]);
System.exit(-1);
}
} else {
System.out.print("Please enter text--> ");
ciphertext = keyboard.nextLine();
}
// -----------------------------------------------------------------
int distance = 0; // how far the ciphertext should be shifted
String next = ""; // user input after viewing
while (!next.equals("quit")) {
String plaintext = "";
distance += 1;
for (int i = 0; i < ciphertext.length(); i++) {
char shift = ciphertext.charAt(i);
if (Character.isLetter(shift)) {
shift = (char) (ciphertext.charAt(i) - distance);
if (Character.isUpperCase(ciphertext.charAt(i))) {
if (shift > '0' && shift < 'A') {
shift = (char) (shift + 26);
plaintext += shift;
} else {
plaintext += shift;
}
}
if (Character.isLowerCase(ciphertext.charAt(i))) {
if (shift > '0' && shift < 'a' && ciphertext.charAt(i) < 't') {
shift = (char) (shift + 26);
plaintext += shift;
} else {
plaintext += shift;
}
}
} else {
plaintext += shift;
}
}
System.out.println(ciphertext);
// At this point, plaintext is the shifted ciphertext.
System.out.println("distance " + distance);
System.out.println(plaintext);
System.out.println("Press enter to see the next option,"
+ "type 'quit' to quit.");
next = keyboard.nextLine().trim();
}
System.out.println("Final shift distance was " + distance + " places");
}
}
...plaintext += shift; } else { plaintext += shift; }
— Это не имеет смысла. Вы можете поместить операторplaintext += shift
вне оператораelse
. - person MC Emperor   schedule 14.02.2017'Z'
и'z'
- это несколько символов, которые не имеют ничего общего с буквами. Вы захотите их пропустить. - person Makoto   schedule 16.02.2017