所以我正在使用教科书学习编码,突然间它给出了一个使用循环的例子,它使用了很多我以前从未涉及过的概念和代码。请有人向我解释什么if (s.charAt(low) != s.charAt(high))
和 int high = s.length() - 1;
是。还有,为什么low = 0
?我还没有学会这个。这是查找回文的代码。谢谢
import java.util.Scanner;
public class Palindrome {
/** Main method */
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a string: ");
String s = input.nextLine();
// The index of the first character in the string
int low = 0;
// The index of the last character in the string
int high = s.length() - 1;
boolean isPalindrome = true;
while (low < high) {
if (s.charAt(low) != s.charAt(high)) {
isPalindrome = false;
break;
}
low++;
high--;
}
if (isPalindrome)
System.out.println(s + " is a palindrome");
else
System.out.println(s + " is not a palindrome");
}
}