私はエクリプスを使用しています。ユーザーが入力した単語を暗号化および復号化するプログラムを作成する必要がありますが、暗号化を選択すると、スレッド "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String で例外が発生します。 Encryption.main(Encryption.java:118) の Encryption.encrypt(Encryption.java:43) の charAt (不明なソース)
これが私のコードです:
import java.util.Scanner;
public class Encryption
{
public static String message = "";
public static boolean hasMessage = false;
public static boolean encrypted = false;
static char a = 0;
static char b;
static int w;
static int x;
static int y;
static int z;
public static void display()
{
System.out.println("Message: " + message + "\n");
}
public static void encrypt(String word)
{
if(!hasMessage)
{
System.out.println("No message");
// Tell the user there is no message
}
else if(encrypted)
{
System.out.println("Message is already encrypted");
// Tell the user the message is already encrypted
}
else
{
message = "";
// Reset the message to blank
for (message.length();;)
{
for (message.charAt(a);; a++)
{
int w = (int) a * 2;
int x = (int) w + 2;
char y = (char) x;
}
}
//get char from each letter (increase char each time), cast as int
}
System.out.println(message);
encrypted = true;
// Using the parameter word, modify message
// to contain a new value following a predictable pattern
// Hint: alter each character's ASCII value by casting
// to an integer and using math operators
// Display the new message
// Set encrypted to true
}
public static void decrypt(String word)
{
if(!hasMessage)
{
System.out.println("No message");
// Tell the user there is no message
}
else if(!encrypted)
{
System.out.println("Message not encrypted");
// Tell the user the message is not encrypted
}
else
{
System.out.println(message);
// Like encrypt, but in reverse
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int menuChoice = 0;
while(menuChoice != 4)
{
System.out.println( "[1] Enter Word\n" +
"[2] Encrypt\n" +
"[3] Decrypt\n" +
"[4] Quit\n");
menuChoice = sc.nextInt();
if(menuChoice == 1)
{
System.out.println("Input message");
message = sc.next();
// prompt user to input message
// assign next word to the class-level variable message
hasMessage = true;
encrypted = false;
// set hasMessage to true
// set encrypted to false
}
else if(menuChoice == 2)
{
encrypt(message);
}
else if(menuChoice == 3)
{
decrypt(message);
}
}
}
}