2

I'm trying to get a program that checks if a string input from the user is a palindrome (task from CodeAbbey). When I type myself input data, it works well, but if strings are put automatically by the site, I'm getting this error:

Exception:

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

The code:

public class Palindromes {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Scanner scanStr = new Scanner(System.in);

        //Number of tests
        int n = scan.nextInt();

        for (int i = 0; i < n; i++) {
            //Getting string
            String s = scanStr.nextLine();

            //Variable for number of letters in string
            int letters = 0;

            //Getting number of letters in string
            for (int j = 0; j < s.length(); j++) {
                if (Character.isLetter(s.charAt(j)))
                    letters++;
            }

            //Array with string characters
            char[] characters = new char[letters];

            //Counter
            int a = 0;
            //Put chars from string to array
            for (int j = 0; j < s.length(); j++) {
                if (Character.isLetter(s.charAt(j))) {
                    characters[a] = s.toLowerCase().charAt(j);
                    a++;
                }
            }

            //Counters
            int x = 0;
            int y = characters.length - 1;
            //Variable for result
            char res = 'Y';

            //If the string is a palindrome
            do {
                if (characters[x] != characters[y])
                    res = 'N';
                x++;
                y--;
            } while (x <= y);

            //Prints result
            System.out.print(res + " ");
        }
    }
}
Milo
  • 3,365
  • 9
  • 30
  • 44
  • Possible duplicate of [java.util.NoSuchElementException: No line found](https://stackoverflow.com/questions/7209110/java-util-nosuchelementexception-no-line-found) – Dushyant Tankariya Sep 03 '19 at 13:26
  • 1
    I would suggest just using one Scanner. I see that you initialize two Scanner objects at the beginning, but you should only need one. I'm not sure how the site is passing in the arguments, though. – SaxyPandaBear Sep 03 '19 at 13:31
  • Could you try with Only one Scanner Object? – Nagesh Tripathi Jun 27 '20 at 09:19

0 Answers0