I have a problem here.

Eg,

do {

method1();
method2();
method3();

while(repeat() );

how do i write the repeat() ??

It's needs to take in user inputs (eg, yes,no,y,n) and convert them into boolean.
If input is yes/y, then it will repeat everything again.
If input is no/n,then it will end the whole thing.

Dani AI

Generated

As asked, you need a small method that reads the user reply and returns true for yes/y and false for no/n. already sketched the idea; here is a compact, robust console implementation that accepts upper/lower case, trims whitespace, and repeats the prompt until it gets a valid answer.

public static boolean promptRepeat(Scanner sc) {
    while (true) {
        System.out.print("Repeat (y/n)? ");
        if (!sc.hasNextLine()) {
            return false; // EOF -> stop
        }
        String line = sc.nextLine().trim().toLowerCase();
        if (line.isEmpty()) {
            continue;
        }
        char c = line.charAt(0);
        if (c == 'y') return true;
        if (c == 'n') return false;
        System.out.println("Please reply y/yes or n/no.");
    }
}

Example usage:

Scanner sc = new Scanner(System.in);
try {
    do {
        method1();
        method2();
        method3();
    } while (promptRepeat(sc));
} finally {
    sc.close(); // close once at program end
}

Notes and common pitfalls: create a single Scanner for System.in and pass it in — do not construct and close a Scanner inside the prompt method (closing it will close System.in for the whole program). If you mix nextInt()/nextDouble() with nextLine(), consume the leftover newline (sc.nextLine()) before prompting. For GUI apps, as mentioned, use a confirm dialog rather than console IO.

Recommended Answers

All 4 Replies

how do i write the repeat() ??

Investigate JOptionPane.showConfirmDialog() if you are working on a GUI proggy.

If it's a console proggy, it's a lil bit more complicated, and I am a lazy writer. :D

public boolean repeat()
{
    //ask user for answer YES, NO
    //if response is yes, return true
    //if not yes, then return false        
}

Can i know how to convert what the user inputs into boolean expression ?

Simple way:


String input = //get input from user

if (input.equals("yes"))

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.