質問

I am trying to write a program to reverse the letters/words in an inputted string, I thought I finally had it but I can't figure out why there are so many excess spaces in front of my output text. Any help would be greatly appreciated.

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?

This is what I have so far and it seems to do exactly what I want it to do minus all the excess white space in front of the output.

 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]);
}
役に立ちましたか?

解決

Try this

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

The issue is you are initializing that char array to size 99. For a string of size 4... we have to print 95 nulls THEN the 4 chars in reverse order. This will be fixed by initializing the array to the actual size of the input string. No nulls to print then (printing nulls results in a white space).

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?

Hmmm. Not sure what you mean? The word "scope" has specific meaning in CS that I don't think is the meaning you are referring to!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top