Reputation: 45
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
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
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