Home How to get the last index from a String in a for loop
Reply: 0

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

user1566
1#
user1566 Published in April 22, 2018, 12:57 am

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 ?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304752 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO