Dunila28
Dunila28

Reputation: 45

incrementing a second variable in a for loop java

I am trying to create a program that checks if a word is a palindrome or not and my issue is that in my for loop the variable j doesn't seem to get any higher than zero even though i am incrementing it (j++). Here is my Code(btw I am new to coding so don't be too harsh):

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter Word");
    String word = scanner.next();
    scanner.close();


    for(int i = word.length(); i>0; i--) {
        int j = 0;

        char modTemp = word.charAt(i-1);
        char wordTemp = word.charAt(j);

        System.out.println("reverse char: "+modTemp);
        System.out.println("Normal char: "+wordTemp);
        System.out.println(j);

        if(modTemp == wordTemp) {
        }

        ++j;

    }

}

Upvotes: 0

Views: 75

Answers (2)

Hasitha Amarathunga
Hasitha Amarathunga

Reputation: 2005

Try this

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter Word");
    String word = scanner.next();
    scanner.close();

    int j = 0;
    for(int i = word.length(); i>0; i--) {    
        char modTemp = word.charAt(i-1);
        char wordTemp = word.charAt(j);

        System.out.println("reverse char: "+modTemp);
        System.out.println("Normal char: "+wordTemp);
        System.out.println(j);

        if(modTemp == wordTemp) {
        }

        ++j;

    }

}

Upvotes: 0

Ruslan
Ruslan

Reputation: 6290

You should define int j = 0 before the for loop. Also nothing stops you to define for loop with 2 variables:

for (int i = word.length(), j = 0; i > 0; i--, j++) {
    ...
}

Upvotes: 1

Related Questions