Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Can someone explain why my loop does not run again even when "y" is entered.

  1. #1
    Junior Member
    Join Date
    May 2022
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Can someone explain why my loop does not run again even when "y" is entered.

    import java.util.Scanner;
    public class EvenOrOdd
    {
    public static void main (String[]args)
    {
    String a = "y";
    while (a.equals("y")){
    Scanner stdin = new Scanner(System.in);
    System.out.print("Enter a number:");
    int x = stdin.nextInt();
    if ( x % 2 == 0)
    {
    System.out.println(x + " is even ");
    }
    else if (x % 2 == 1)
    {
    System.out.println(x + " is odd ");
    }
    System.out.println("Enter y to play again, n to quit(y/n):");
    a = stdin.next();
    }
    }

    }

  2. #2
    Member
    Join Date
    Apr 2022
    Posts
    36
    Thanks
    0
    Thanked 8 Times in 8 Posts

    Default Re: Can someone explain why my loop does not run again even when "y" is entered.

        public static void main (String[]args) {
            String a = "y";
            while (a.equalsIgnoreCase("y")) {
                Scanner stdin = new Scanner(System.in);
                System.out.print("Enter a number: ");
                int x = stdin.nextInt();
                System.out.println( x % 2 == 0 ? x + " is even" : x + " is odd");
                System.out.println("Enter y to play again, n to quit(y/n): ");
                a = stdin.nextLine();
            }
        }

Similar Threads

  1. Replies: 1
    Last Post: August 20th, 2019, 07:07 AM
  2. Replies: 1
    Last Post: July 16th, 2014, 04:16 AM
  3. Replies: 2
    Last Post: May 22nd, 2014, 01:17 PM
  4. Trying to get an "if" statement to work in a "for loop".
    By JAKATAK in forum What's Wrong With My Code?
    Replies: 4
    Last Post: April 1st, 2013, 11:16 PM
  5. Explain, "Java is NOT an internet version of C++"?
    By wikki2013 in forum Java Theory & Questions
    Replies: 7
    Last Post: March 14th, 2013, 12:27 PM