java - 什么 (s.charAt(low) != s.charAt(high)) {" and " int high = s.length() - 1;
问题描述
所以我正在使用教科书学习编码,突然间它给出了一个使用循环的例子,它使用了很多我以前从未涉及过的概念和代码。请有人向我解释什么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");
}
}
解决方案
假设,您输入文本,Hello
.
文本的长度,Hello
是5
int high = s.length() - 1
表示您将4
(即 5 - 1)存储到变量high
. a 中第一个字符的索引String
是0
。因此,in 的索引是H
,isHello
的0
索引等等。因此,最后一个字符的索引等于。e
1
o
4
"Hello".length() - 1
在while
循环的第一次迭代中,条件 ,if (s.charAt(low) != s.charAt(high))
将文本的第一个字符 (ie H
) 与最后一个字符 (ie o
) 进行比较,Hello
; 因为 is 的值和low
is0
的high
值4
。这也回答了你的问题,
为什么低= 0?
如果 index 处0
的字符等于 index 处的字符4
,则 的值low
将递增到1
并且 的值high
将递减到3
以便在while
循环的下一次迭代中,索引处的字符1
(即第二个字符)可以与索引处的3
(即倒数第二个字符)进行比较。然而,在这种情况下(即当输入为 时)Hello
,在第一次迭代本身中,导致循环(即停止执行下一次迭代)。s.charAt(low) != s.charAt(high)
true
while
break
我建议您从一个好的教程中了解 Java 的基础知识,例如https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html
祝你一切顺利!
推荐阅读
- git - 通过 Git Bash 访问桌面
- r - 在几何线中以不同比例绘制辅助轴
- angular - 无法将具有 Angular Universal 的 Angular 9 应用程序部署到具有 Firebase 功能的 Firebase
- java - JSON 映射集合到 ArrayList
- ruby-on-rails - lazyload-rails 显示扭曲的 PNG
- google-analytics - 是不是像加 onclick=”ga('send', 'event', 'Category', 'Action', 'Label', 'Value');》这么简单 到我的链接以跟踪点击事件?
- postgresql - 在 Postgres 的另一列中获取具有最大字符串长度的行
- javascript - Discord.js V12 如何显示具有特定角色的所有成员?
- node.js - 如果在 NodeJS 中未确认电子邮件,则自动删除 Mongo 文档
- java - 检测到错误的 Node.js 版本