我需要这个回文的解释

I need an explanation for this palindrome

任何人都可以举例说明 "for loop" 中的这个回文吗?我不明白for循环是如何工作的,如果你们能帮助我理解,那就太好了。

 import java.util.*;`
 public class palindrome {

public static void main(String args[])
{
  String original, reverse = "";


  Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
  original = in.nextLine();

  int x = original.length();

  for ( int i = x - 1; i >= 0; i-- ){
     reverse  = reverse + original.charAt(i);
  }

   if (original.equals(reverse))
     System.out.println("Entered string is a palindrome.");
  else
     System.out.println("Entered string is not a palindrome.");
    }
    }   

它只是以向后的方式一次一个地读取输入字符串的字符,并将它们连接成一个空字符串。

之后就是对比了。

randomtest
         ^  start here ( x-1 ) cuz x is full lenght, not index

randomtest
     <--^    and go backwards (i--)

变量X是原始字符串的长度。由于索引从 0 开始,这意味着最后一个字符的索引是 (x-1)。因此,for 循环使用变量 i = x-1 进行初始化,以便使循环从字符串的最后一个字符开始。

从那里它将索引 i 处的字符(此时是字符串中的最后一个字符)添加到新的空白字符串中。然后它检查 i 是否大于或等于 0(检查字符串是否还有更多字符或是否已到达开头)。如果条件为真(还有更多字符要处理),它会将 i 的值减 1,以获取字符串中的倒数第二个元素。然后它将其添加到反向字符串中,并再次检查。依此类推,直到到达字符串的开头。

如果你有输入字符串 "FooBar" 它的工作原理如下:

长度 = 6

我=6-1=5

是 5 >= 0 吗?是的。 进入循环

反转+=字符串(5) //反向= "r"

减少 i.

我=4

是 4 >= 0 吗?是的 反向 += 字符串(4) //反向= "ra"

减少我

我=3

//等等。直到我低于零

结束循环

反转="raBooF"

这有帮助吗?

 // let's assume 
 // String original = "question" (some random String)
 // this assigns length of the string into int variable x

 int x = original.length(); // x = 8



  // for loop starts here
  // for ex - if length of string "question" is 8 (index will be from 0 to 7)
  // so, it has to starts from last index i.e 7, which is nothing but (8-1) or (length-1) index

  // it will start from i = 7, since 7th character gives last character i.e 'n'
  // so this for loop starts picking up one character from last
  // value of 'i' (index) is decreased every time.


for ( int i = x - 1; i >= 0; i-- ){
     // in this step the character is picked (present at 'i'th index) and 
     // added to the 'reverse' string and overwritten to the 'reverse' object
     // for ex - 
     // if loop starts from i = 7, original.charAt(7) will be n in String "question", then reverse will be reverse ("" (empty string)) + 'n' which is "n"
     // next time reverse will be "n" and i will be = 6, then original.charAt(6) will be = 'o'.
     // since concatenation of reverse and original.charAt(i) has to be assigned to reverse, the new reverse will be = "no" 
     // when i = 5, reverse = "no" + 'i' = "noi"
     // i = 4,  reverse = "noi" + 't' = "noit"
     // i = 3,  reverse = "noit" + 's' = "noits"
     // i = 2,  reverse = "noits" + 'e' = "noitse"
     // i = 1,  reverse = "noitse" + 'u' = "noitseu"
     // i = 0,  reverse = "noitseu" + 'q' = "noitseuq"
     // when i = -1, loop exits, so reverse String will have "noitseuq" after for loop ends
     reverse  = reverse + original.charAt(i);
  }