我正在尝试编写一个程序来反转输入字符串中的字母/单词,我想我终于有了它但我无法弄清楚为什么输出文本前面有这么多多余的空格。任何帮助将不胜感激。
另外在旁注中,我试图使数组的范围成为递增的变量,但它不会运行,但是我可以使用递增的变量作为索引位置而没有任何问题;那是为什么?
这就是我到目前为止所做的事情,似乎正是我想做的事情,减去输出前面所有多余的空白区域。
Scanner in = new Scanner(System.in);
System.out.println("please enter string");
String strName = in.nextLine();
int ap = 0;
char strArray[] = new char[99];
for(int i=0;i < strName.length();i++)
{
strArray[ap] = strName.charAt(i);
ap++;
}
for (int e=strArray.length-1;e >= 0;e--)
{
System.out.print(strArray[e]);
}
答案 0 :(得分:1)
试试这个
Scanner in = new Scanner(System.in);
System.out.println("please enter string");
String strName = in.nextLine();
int ap = 0;
char strArray[] = new char[strName.length()];
for(int i=0;i < strName.length();i++)
{
strArray[ap] = strName.charAt(i);
ap++;
}
for (int e=strArray.length-1;e >= 0;e--)
{
System.out.print(strArray[e]);
}
问题是你正在将char数组初始化为99.对于大小为4的字符串...我们必须以相反的顺序打印95个空值,然后打印4个字符。这将通过将数组初始化为输入字符串的实际大小来修复。然后没有要打印的空值(打印空值会产生空格)。
Also on a side note I attempted to make the scope of the array an incremented variable but it
would not run, however I can use an incremented variable for the index position without any
issues; why is that?
嗯。不明白你的意思? “范围”一词在CS中具有特定含义,我认为这并不是您所指的意思!