Answer the question
In order to leave comments, you need to log in
Why is the execution of this program interrupted?
Hello, I am writing a program that encrypts a message using a Caesar cipher, I encountered one problem after entering the sdvig variable, the program execution is interrupted, no error messages appear, what could be the reason for this?
package zadachi;
import java.util.Scanner;
public class wwwwww {
static int sdvig;
static char[] alphabet;
private static Scanner in;
public static void main(String[] args){
in = new Scanner(System.in);
sdvig = in.nextInt();
byte x = 0; // Для заполнения массива с зашифрованным сообщением и для перебора
alphabet = new char[] {'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'};
String message = in.nextLine();
message = message.toLowerCase();
char[] m = message.toCharArray(); // Незашифрованное сообщение
char[] messageShifr; // Объявление массива с зашифрованным сообщением
messageShifr = new char[m.length];
int mes_len = m.length;
while (mes_len != x) { //шифрование
byte element = plunk(m[x]);
if (element < 51 && element > -25) {
if (element > 25) {
element = (byte) (-25 + element);
messageShifr[x] = alphabet[element];
x++;
}
else {
if (element < 0) {
element = (byte) (25 + element);
messageShifr[x] = alphabet[element];
x++;
}
else {
messageShifr[x] = alphabet[element];
x++;
}
}
}
else {
messageShifr[x] = m[x];
x++;
}
}
for (int y = 0; y < messageShifr.length; y++) { //вывод зашифрованного сообщения
System.out.print(messageShifr[y]);
}
}
public static byte plunk(char k) { // перебирает alphabet в посиках совпадений с k
byte i = 0;
while (i != 26) {
if (alphabet[i] == k) {
break;
}
else {
i++;
}
}
return (byte) (i + sdvig);
}
}
Answer the question
In order to leave comments, you need to log in
String message = in.nextLine();
while(message.length()==0) message=in.nextLine();
or through in.next() read words one by one
If I remember correctly nextInt() reads a number, but leaves a newline character, and nextLine() reads just up to this character, so it turns out that your message becomes empty and the program performed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question