我有一个程序,据说
- 提示用户输入单词、短语或句子。
- 然后我应该“加密”您输入的内容 13 次,并每次都打印。最后打印的内容应该与用户输入匹配。
- 我只能加密字母字符。其他一切保持不变。
- 通过查找每个字符的 ASCII 值然后将其增加 2 来“加密”。如果字母更改大小写,则使其从小写的 a 或大写的 A 开始。
我的代码现在只给我 1 加密,并在 2 处停止。它也只适用于第一个字母。我的类(class)还没有学过数组,但是如果我们愿意的话我们可以尝试一下。
import java.util.Scanner;
public class Encrypt{
Scanner keyboard = new Scanner(System.in);
String message = new String();
String g = new String();
char y;
public void input(){
System.out.printf("Welcome to Encrypt.java. Please enter a word,phrase, or sentence. \n");
System.out.println();
System.out.print("-> ");
message = keyboard.nextLine();
}
public void code(){
int x = message.length()-1;
boolean enter = true;
for(int i = 0; i <= x; i++){
int j = message.charAt(i);
if((j >= 32 && j <=64) ||
(j >= 91 && j <=96) ||
(j >= 123 && j <= 127)){
}
else if((j >= 65 && j <= 90)){
j = j + 2;
if(j>90){
j = (j-90)+64;
}
}
else if(j>=97 && j <= 122){
j = j + 2;
if(j>122){
j = (j-122) + 96;
}
}
if(enter == true){
System.out.println();
System.out.print(" ");
enter = false;
}
y = (char)(j);
g = g + y;
message = g;
x = message.length()-1;
}
System.out.print(g);
System.out.println();
}
public void print(){
for(int i = 1; i <= 13; i ++){
System.out.println("Encryption " + i + ":");
this.code();
}
}
public static void main(String [] args){
Encrypt e = new Encrypt();
e.input();
e.print();
}
}
最佳答案
两件事:
- 每次迭代后重置变量 g。
- 消息的正确放置。
public void code() {
int x = message.length() - 1;
boolean enter = true;
g = "";
for (int i = 0; i <= x; i++) {
int j = message.charAt(i);
if ((j >= 32 && j <= 64) || (j >= 91 && j <= 96)
|| (j >= 123 && j <= 127)) {
}
else if ((j >= 65 && j <= 90)) {
j = j + 2;
if (j > 90) {
j = (j - 90) + 64;
}
} else if (j >= 97 && j <= 122) {
j = j + 2;
if (j > 122) {
j = (j - 122) + 96;
}
}
if(enter == true){
System.out.println();
System.out.print(" ");
enter = false;
}
y = (char) (j);
g = g + y;
}
message = g;
}
输出:
Welcome to Encrypt.java. Please enter a word,phrase, or sentence.
-> abba
Encrypt.code() message >> abba
Encrypt.code() message >> cddc
Encrypt.code() message >> effe
Encrypt.code() message >> ghhg
Encrypt.code() message >> ijji
Encrypt.code() message >> kllk
Encrypt.code() message >> mnnm
Encrypt.code() message >> oppo
Encrypt.code() message >> qrrq
Encrypt.code() message >> stts
Encrypt.code() message >> uvvu
Encrypt.code() message >> wxxw
Encrypt.code() message >> yzzy
关于java - Java 的基本字符串帮助(这里是新手),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672232/