gpt4 book ai didi

java - java打印文本前面多余的空格

转载 作者:太空宇宙 更新时间:2023-11-04 06:58:57 26 4
gpt4 key购买 nike

我正在尝试编写一个程序来反转输入字符串中的字母/单词,我以为我终于有了它,但我不明白为什么我的输出文本前面有这么多多余的空格。任何帮助将不胜感激。

另外,我试图将数组的范围设置为递增变量,但它不会运行,但是我可以使用递增变量作为索引位置,没有任何问题;这是为什么?

这就是我到目前为止所拥有的,它似乎完全按照我想要的方式进行,减去输出前面的所有多余空白。

 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]);
}

最佳答案

试试这个

 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]);
}

问题是您正在将该字符数组初始化为大小 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中有特定的含义,我认为这不是你所指的含义!

关于java - java打印文本前面多余的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22368171/

26 4 0
文章推荐: java - 如何为 @Async 方法使用自定义执行器?
文章推荐: html - Shift
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com