【发布时间】:2015-10-24 19:02:40
【问题描述】:
有一个分配,其中我必须将字符串中的每个索引增加用户设置的数量以生成新名称。
换句话说:
输入你的名字: 海伦李 键入要递增的整数: 1 新名称:gfmfo!mff
因此,使“helen lee”中的每个索引都增加 1。
这就是问题所在。 Java 将字符串中的每个索引视为一个字符。甚至空格。 因此,当我将“*whitespace”增加 2 时,它将产生“@”。
但是
当我将空格增加 5 时,会发生错误。 (应该产生“%”)。 有没有其他方法可以在不调用错误的情况下将空格增加 5?
这是我的代码:
String alpha = " ";
int integer = 0;
System.out.println("Question 1: ");
Scanner alphaInput = new Scanner(System.in);
System.out.println("Please enter your name. ");
alpha = alphaInput.nextLine();
Scanner intInput = new Scanner(System.in);
System.out.println("How many cycles to cycle your name: ");
integer = intInput.nextInt();
int stringIndex = alpha.length();
char newName;
System.out.printf("Your new name is: ");
for(int i = 0; i < stringIndex; i++)
{
newName = (char) (alpha.charAt(i) + integer);
System.out.printf("" + newName);
};
【问题讨论】:
-
旁注:您不需要在每次请求输入时都实例化新的
Scanners。只需重新使用旧的
标签: java string char whitespace increment