私はJavaで簡単な暗号化プログラムをやっています。ユーザーが文字列(strTarget)を入力すると、その文字列がこの関数に渡されます。 forループでは、文字のASCII値を4にしてから文字列に戻す必要があります(文字列内のすべての文字についてこれを行います)。あなたが私の友人を見て、私はすでにそれを行っている、しかし、私は戻って(例えば、ユーザが 'efg'を入力した場合、返された文字列は 'abc'になる必要があります)文字列を返す方法
私が提案した結果は次のとおりです。私は明らかに何が間違ってメニュークラスでは、それが何であるかわからない。私は暗号化する文字列を入力すると動作を停止します。
import java.util.Scanner;
public class Menu {
public static String strTarget;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out
.println("Welcome to the encr/decr program");
System.out
.println("To encrypt a string, press 1, to decrypt a string, press 2");
int choice = in.nextInt();
if (choice == 1) {
System.out.println("Type the string you want to encrypt.");
strTarget = in.next();
System.out.println(Encrypt(strTarget));
}
if (choice == 2) {
System.out.println("Enter the string you want to decrypt.");
}
}
private static String Encrypt(String strTarget) {
// TODO Auto-generated method stub
int len = strTarget.length()-1;
String destination = "";
for (int i = 0; i<len; i++)
{
if (strTarget.charAt(i) != ' ')
{
char a = strTarget.charAt(i);
int b = (int) a;
b = strTarget.charAt(i)-4;
a = (char) b;
if (b<70 && b>64)
{
b = strTarget.charAt(i)+26;
a = (char) b;
destination += a;
}
}
}
return destination;
}}
EDIT:完全なプログラムを追加しました。
import java.util.Scanner;
public class Menu {
public static String strTarget;
public static String destination = "";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the encr/decr program");
System.out.println("To encrypt a string, press 1, to decrypt a string, press 2");
int choice = in.nextInt();
if (choice == 1) {
System.out.println("Type the string you want to encrypt.");
strTarget = in.next();
StringBuilder zomg = new StringBuilder(strTarget);
System.out.println(Encrypt(zomg));
}
if (choice == 2) {
System.out.println("Enter the string you want to decrypt.");
}
}
private static String Encrypt(StringBuilder zomg) {
// TODO Auto-generated method stub
int len = strTarget.length()-1;
for (int i = 0; i<len; i++)
{
if (strTarget.charAt(i) != ' ')
{
char a = strTarget.charAt(i);
int b = (int) a;
b = strTarget.charAt(i)-4;
a = (char) b;
destination += a;
if (b<70 && b>65)
{
b = strTarget.charAt(i)+26;
a = (char) b;
destination += a;
}
}
}
System.out.println(destination);
return destination;
}}
は、私はあなたが(私が思う)と変更を加えて、それが仕事に始めるが、それがすることになっているとして、それが機能していません。意味が分からないような結果が得られます( 'A'の場合、 'V'の場合は戻って 'V'の場合)。助言がありますか?
リリースJDK 5では、StringBufferには、単一のスレッドStringBuilder用に設計された同等のクラスが追加されました。 StringBuilderクラスは、同じ操作のすべてをサポートしますが、同期を実行しないため、より高速ですので、一般的にこれに優先して使用する必要があります。 http://docs.oracle.com/javase/6/docs/api/java/lang/StringBufferhtml – SHiRKiT
最適なパフォーマンスを得るには、あらかじめわかっているように、適切な容量のストリングビルダを作成してください。 –