Issue
I am trying to make a program that sees if a word is a palindrome or not. However, I am getting the above error. When I run the program it puts together the word backwards, up until there are no more letters left. That is when I get the error.
// Programmer: Your name
// Class, Section and Term: ...
// Purpose: Find the average of a list of integer numbers. The list is ended with a sentiel value SENTINEL.
// Topic: while-loop
// Import the Scanner Class for input operations.
import java.util.Scanner;
public class SimpleProgram {
public static void main(String[] args) {
// Create the Scanner object, scnr, to perform input operations.
Scanner scnr = new Scanner(System.in);
// Declare the identifiers
String reverse;
reverse = "";
int index;
int number;
String letter;
final String end = "Stop";
System.out.println("Please type a word:");
letter = scnr.next();
index = letter.length() + 0;
while (!letter.equals(reverse) || (index >= 0)) {
// while (letter.equals(reverse.length() + 0));
index--;
// index = letter.length()-1 - index--;
// index + 1;
// System.out.println(index.CharAt(index--));
reverse = reverse + letter.charAt(index);
System.out.println(reverse);
}
if (letter.equals(reverse)) {
System.out.println(letter + " is a palindrome!");
}
else {
System.out.println(letter + " is not a palindrome, spelt backwards it is: " + reverse);
}
scnr.close();
}
}
Solution
You need just the change the while condition look at my edition it's works !!
public static void main(String[] args) {
// Create the Scanner object, scnr, to perform input operations.
Scanner scnr = new Scanner(System.in);
// Declare the identifiers
String reverse;
reverse = "";
int index;
int number;
String letter;
final String end = "Stop";
System.out.println("Please type a word:");
letter = scnr.next();
index = letter.length() - 1;
while (!letter.equals(reverse) && (index >= 0)) {
// while (letter.equals(reverse.length() + 0));
// index = letter.length()-1 - index--;
// index + 1;
// System.out.println(index.CharAt(index--));
reverse = reverse + letter.charAt(index);
System.out.println(reverse);
index--;
}
if (letter.equals(reverse)) {
System.out.println(letter + " is a palindrome!");
}
else {
System.out.println(letter + " is not a palindrome, spelt backwards it is: " + reverse);
}
scnr.close();
result :
olaalo is a palindrome!
Answered By - Med Elgarnaoui
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.