user2999650
user2999650

Reputation: 1

java rerun program not working with do while loop

just started java, eclipse

I want the program to contine only if 'y' or 'Y' is pressed

if any other key is pressed end program

please help

import java.io.*;


public class TicketMaster{

public static void main(String args[]) throws IOException{

    char choice;

    do{
        choice ='\0'; //clear char
        System.out.println("First Test \t\t" + choice);

        //rerun program
        System.out.println("Run Program Again: ");
        choice = (char) System.in.read();

        //testing
        if(choice == 'y' || choice == 'Y')
            System.out.println("Contine \t\t" + choice);
        else
            System.out.println("End Program \t\t" + choice);


        System.out.println("\n\n\n");
    }
    while(choice == 'y' || choice == 'Y');


} //end main method
} //end class

Upvotes: 0

Views: 1174

Answers (4)

Reimeus
Reimeus

Reputation: 159844

Since read only reads a single character from the InputStream you will need to manually consume the newline character

choice = (char) System.in.read();
System.in.read(); // added - consumes newline

Upvotes: 0

brindy
brindy

Reputation: 4695

Sadly, Java doesn't usually support what I think you're trying to do, which I believe is to detect a key press on the console, without pressing enter. See this answer for discussions on how this might be achieved.

Upvotes: 0

rgettman
rgettman

Reputation: 178293

The problem appears to be that the program ends even though 'Y' or 'y' is entered.

The cause is that no input will be sent to Java until you press Enter. This places an entire line of input and a newline character(s) on the input stream.

The first iteration of the while loop correctly recognizes the 'y' or 'Y', but the next loop immediately runs and detects the newline character(s) which doesn't match.

Switch to using a Scanner so you can can call nextLine() to read an entire line of input at once, and you can extract the first character of the String to see if it's 'y' or 'Y'. This will discard the newline character(s).

Upvotes: 2

piacente.cristian
piacente.cristian

Reputation: 777

Use this code:

    if(choice == 'y' || choice == 'Y')
        System.out.println("Contine \t\t" + choice);
    else{
        System.out.println("End Program \t\t" + choice);
        System.exit(0);
    }

or this if you don't want the program to exit completely, but just to break the while loop

    if(choice == 'y' || choice == 'Y')
        System.out.println("Contine \t\t" + choice);
    else{
        System.out.println("End Program \t\t" + choice);
        break;
    }

Upvotes: 1

Related Questions