简体   繁体   中英

How to get the last index from a String in a for loop

I am trying to make a program which checks if input String is palindrome. I finally managed to do it converting it to char array first, but I couldn't figure out how to access the last index from the String in for loop.

import java.util.Scanner;

public class Task8 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        boolean isPalindrome = true;

        System.out.println("Please, enter string!");
        String str = sc.nextLine();
        char[] chars = str.toCharArray();

        for (int i = 0; i < chars.length; i++) {            
            if(chars[i]!= chars[chars.length-i-1]){
                isPalindrome = false;
                break;
            }
        }
        if(isPalindrome){
            System.out.println("It is palindrome!");
        }
        if(!isPalindrome){
            System.out.println("It isnt a palindrome!");
        }
    }
}

This is the final result it it looks like it is working, but eclipse returns errors if I try something like:

for(int i = 0; i < str.length(); i++){
        if(str.charAt(i)!= str.charAt(str.length(-1-i)){
            isPalindrome = false;
            break;
        }
    }

It is working if i put -1-i outside the the braces (str.charAt(i)!= str.charAt(str.length()-1-i)) , but why on the first index it lets me put i in the braces and for the last index I can't use i and -1 inside braces ?

The length() method doesn't take any parameters. It's the charAt(...) method that takes an index parameter.

And btw it's enough to go until the middle of the input string.

for (int i = 0; i < str.length() / 2; i++) {
    if (str.charAt(i) != str.charAt(str.length() -i - 1)) {
        isPalindrome = false;
        break;
    }
}

str.length(-1-i)语法不正确, str.length() API不接受任何参数,其唯一目的是为您提供给定字符串的长度。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM