【发布时间】:2019-12-01 12:14:54
【问题描述】:
所以我正在使用教科书学习编码,突然它给出了一个使用循环的示例,它使用了很多我以前从未涉及过的概念和代码。请有人向我解释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");
}
}
【问题讨论】:
-
Java 之于 Javascript 就像 Pain 之于绘画,或者 Ham 之于仓鼠。它们完全不同。强烈建议有抱负的编码人员尝试学习他们尝试编写代码的语言的名称。当您发布问题时,请适当地标记它 - 这可以让那些了解您需要帮助的语言的人看到您的问题。