【发布时间】:2018-07-16 17:31:42
【问题描述】:
Caesar Cipher 单独应用于字符串中的每个字母。每个字母必须在字母表中向前移动 n 步。如果一个字母从字母表的末尾('z')移开,那么它会一直移回字母表的开头('a')。 `
import java.util.*;
class question7{
public static void main (String[] args ){
String str = "";
//allowing program to take user input using the keyboard
Scanner kb = new Scanner(System.in);
Scanner s = new Scanner(System.in);
int n = 0;
System.out.println("increasing the letters in string by n");
while (true){
System.out.println("Please enter your string");
str = kb.nextLine();
System.out.println("Please enter your n value");
n = s.nextInt();
String incrementedword=new String();
for (int i=0;i<str.length();i++){
incrementedword+=(char)(str.charAt(i)+n);
}
System.out.println ("your word is "+incrementedword);
}
}
}
例如,以下输入 (“hello world”,1) 应返回“ifmmp xpsme”
但是当我输入 (“hello world”,1) 时,输出是“ifmmp!xpsme”
我做错了什么?
【问题讨论】:
-
您还“增加”了空格字符。排除它!
-
另外,您的代码不适用于“z”。
-
我希望 'z' 是 'a',但 'z' 会是 ' { ',我有点迷茫
-
如果你将 1 加到 'z',Java 不会自动回绕回 'a',也不会自动排除空格和其他非字母字符。你必须告诉它做这些事情。
-
你需要一些
ifs:if (Character.isLetter(str.charAt(i))) {....}
标签: java string caesar-cipher