how can i rerun the program using 'y' and 'n'??

package com.company;

    import java.util.Scanner;

    public class Main {
        public static void main(String[] args) {
            Scanner reader = new Scanner(System.in);
                while (true) {
                    System.out.print("Enter a number: ");
                    int num = reader.nextInt();

                    if (num > 0) {
                        String number = (num % 2 == 0) ? "even number" : "odd number";
                        System.out.println(num + " is " + number);
                        break;
                    }
                    if (num < 0) {
                        System.out.print("Please enter a positive number. ");
                        System.out.print("\n\n");
                    }
                }
            }
        }

Recommended Answers

All 3 Replies

Try declaring a boolean variable initialized to true, and use that instead of true in the while() condition. Then, at the end of the loop, add a call to reader.NextChar(), then use a comparison against 'y' to set the boolean's value.

package com.company;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        Boolean condition = true;
            while (condition) {
                System.out.print("Enter a number: ");
                int num = reader.nextInt();

                if (num > 0) {
                    String number = (num % 2 == 0) ? "even number" : "odd number";
                    System.out.println(num + " is " + number);
                }
                if (num < 0) {
                    System.out.print("Please enter a positive number. ");
                    System.out.print("\n\n");
                }
                System.out.println("Want to again?(Y/N)");
                String judge = new Scanner(System.in).next();
                if (judge.equals("N")) {
                    condition = false;
                }else if (judge.equals("Y")) {
                    condition = true;
                }else {
                    continue;
                }
            }
        }
    }

Two problems with that code:

It creates a second Scanner (line 20). Two Scanners on the same input stream is a formula for chaos. Either of them may read ahead from the stream thus preventing the other from seeing those characters, with unpredictable results. One program -> one Scanner(System.in).

It treats all invalid values of judge (eg "no") as equivalent to "Y"
The else continue does nothing. Line 26 should do some kind of error handing for invalid inout.

(But please let me thank you for posting clean correctly indented code - you;ld be surprised what tat some people post)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.