将 "whitespace" 递增“5”次会导致错误?
Incrementing "whitespace" for "5" times will cause an error?
有一个作业,我必须将字符串中的每个索引递增用户设置的数量以生成新名称。
换句话说:
输入你的名字:
海伦·李
输入要递增的整数:
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);
};
问题是你使用了System.out.printf
。该方法将 %
解释为特殊值,并需要更多数据。您应该改用 System.out.print
(不带 f)。有关详细信息,请参阅 printf
的 documentation。
有一个作业,我必须将字符串中的每个索引递增用户设置的数量以生成新名称。
换句话说:
输入你的名字: 海伦·李 输入要递增的整数: 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);
};
问题是你使用了System.out.printf
。该方法将 %
解释为特殊值,并需要更多数据。您应该改用 System.out.print
(不带 f)。有关详细信息,请参阅 printf
的 documentation。