我需要对这个回文进行解释

时间:2015-03-06 15:38:43

标签: java for-loop palindrome

任何人都可以从" for循环"解释我这个palandrome举个例子?我不明白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.");
    }
    }   

3 个答案:

答案 0 :(得分:0)

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

之后是比较。

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

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

答案 1 :(得分:0)

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

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

如果你有输入字符串&#34; FooBar&#34;它的工作原理如下:

长度= 6

i = 6-1 = 5

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

反向+ =字符串(5) // reverse =&#34; r&#34;

减少我。

i = 4

是4> = 0?是 反向+ =字符串(4) // reverse =&#34; ra&#34;

减少我

i = 3

//等。直到我低于零

结束循环

反向=&#34; raBooF&#34;

这有帮助吗?

答案 2 :(得分:0)

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