【问题标题】:whats (s.charAt(low) != s.charAt(high)) {" and " int high = s.length() - 1;什么 (s.charAt(low) != s.charAt(high)) {" and " int high = s.length() - 1;
【发布时间】: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 之于仓鼠。它们完全不同。强烈建议有抱负的编码人员尝试学习他们尝试编写代码的语言的名称。当您发布问题时,请适当地标记它 - 这可以让那些了解您需要帮助的语言的人看到您的问题。

标签: java string loops


【解决方案1】:

让我们假设,您输入文本 Hello

文本长度,Hello5

int high = s.length() - 1 表示您将4(即5 - 1)存储到变量highString 中第一个字符的索引是0。因此,HelloH的索引为0e的索引为1,以此类推。因此,最后一个字符的索引o4,等于"Hello".length() - 1

while 循环的第一次迭代中,条件if (s.charAt(low) != s.charAt(high)) 将第一个字符(即H)与文本的最后一个字符(即oHello 进行比较;因为low 的值为0high 的值为4。这也回答了你的问题,

为什么低 = 0?

如果索引0 处的字符等于索引4 处的字符,low 的值将增加到1high 的值将减少到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

祝你一切顺利!

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多