首页 > 解决方案 > 什么 (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");
    }
}

标签: javastringloops

解决方案


假设,您输入文本,Hello.

文本的长度,Hello5

int high = s.length() - 1表示您将4(即 5 - 1)存储到变量high. a 中第一个字符的索引String0。因此,in 的索引是H,isHello0索引等等。因此,最后一个字符的索引等于。e1o4"Hello".length() - 1

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

为什么低= 0?

如果 index 处0的字符等于 index 处的字符4,则 的值low将递增到1并且 的值high将递减到3以便在while循环的下一次迭代中,索引处的字符1(即第二个字符)可以与索引处的3(即倒数第二个字符)进行比较。然而,在这种情况下(即当输入为 时)Hello,在第一次迭代本身中,导致循环(即停止执行下一次迭代)。s.charAt(low) != s.charAt(high)truewhilebreak

我建议您从一个好的教程中了解 Java 的基础知识,例如https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html

祝你一切顺利!


推荐阅读