0

A palindrome is a word that reads the same backward or forward. Write a function that checks if a given word is a palindrome. Character case should be ignored.

I created a method isPalindrome(String word) which checkes if passed string is palindrome and return boolean value. For example, isPalindrome("Deleveled") should return true as character case should be ignored, resulting in "deleveled", which is a palindrome since it reads the same backward and forward.

This is the error:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at Main.main(Main.java:20)

My code is:

import java.util.Scanner;
public class Main{
    static boolean isPalindrome(String word){
        int c=word.length()-1;
        boolean flag = false;
        for(int i=0; i<word.length(); i++){
            if(word.charAt(i)==word.charAt(c))
                flag=true;
            else
                return false;
            c--;
        }
        return flag;
    }

     public static void main(String []args){
        Scanner scan = new Scanner(System.in);
        String word= scan.nextLine();
        System.out.println(isPalindrome(word));
        scan.close();
     }
}
Vikas
  • 6,868
  • 4
  • 27
  • 41
  • 1
    I did not get any Exception when running your code – Vikas Apr 20 '19 at 10:28
  • How are you running this code? Is it perhaps on some site/online-editor? In that case you may need to search for area for data which will be passed as standard input, otherwise it would be empty (which would explain exception). – Pshemo Apr 20 '19 at 10:49

2 Answers2

0

Your code is fine. You just need to make a word either lowercase or uppercase before comparing.

static boolean isPalindrome(String word){
        word=word.toLowerCase();  //Added this
        int c=word.length()-1;
        boolean flag = false;
        for(int i=0; i<word.length(); i++){
            if(word.charAt(i)==word.charAt(c))
                flag=true;
            else
                return false;
            c--;
        }
        return flag;
    }
Vikas
  • 6,868
  • 4
  • 27
  • 41
0

Add the scan.hasNextLine() before calling scan.readLine()