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

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

Georgi Michev
Georgi Michev Published in 2017-12-07 21:33:57Z

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;
            System.out.println("It is palindrome!");
            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;

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 ?

janos Reply to 2017-12-07 21:37:43Z

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;
Pankaj Gadge
Pankaj Gadge Reply to 2017-12-07 21:38:28Z

str.length(-1-i) is not a correct syntax, str.length() API doesn't accept any arguments and it's sole purpose is to give you the length of the given string.

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO