Search code examples
javaeofpalindrome

Java palindrome until EOF


I have a program that is supposed to ask the user for a number and it will determine whether it is a palindrome or not. It's supposed to keep asking for numbers until EOF is input - So far it asks for the number twice and doesn't seem to be doing the while loop correctly.

Any insight is appreciated

import java.util.Scanner;
public class PalindromeEOF
{
public static void main(String args[])
{
    Scanner scanner = new Scanner(System.in);        
    System.out.println("Enter a number to check if it is a palindrome:");

    String num = scanner.nextLine();
    String reverse = "";

    while (scanner.hasNextLine())
    {
        for ( int i = 0; i<num.length(); i++ )
        {
            reverse = num.charAt(i) + reverse;
        }
        if (num.equals(reverse))
        {
            System.out.println("\nEntered number IS a palindrome.");
        }
        else
        {
            System.out.println("\nEntered number is NOT a palindrome.");
        }
        System.out.println("\nEnter a number to check if it is a palindrome:");
        num = scanner.nextLine();
        reverse = "";
    }
    System.out.println("\nProgram ended on request");
}
}

Solution

  • This worked for me; unless you need num or reverse outside the while loop it should work.

    import java.util.Scanner;
    public class PalindromeEOF
    {
        public static void main(String args[])
        {
            Scanner scanner = new Scanner(System.in);        
            System.out.println("Enter a number to check if it is a palindrome:");
    
            while (scanner.hasNextLine())
            {
                String num = scanner.nextLine();
                String reverse = "";
    
                for ( int i = 0; i<num.length(); i++ )
                {
                    reverse = num.charAt(i) + reverse;
                }
                if (num.equals(reverse))
                {
                    System.out.println("\nEntered number IS a palindrome.");
                }
                else
                {
                    System.out.println("\nEntered number is NOT a palindrome.");
                }
                System.out.println("\nEnter a number to check if it is a palindrome:");
    
            }
            System.out.println("\nProgram ended on request");
        }
    }