0

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
Ashot Karakhanyan
  • 2,734
  • 3
  • 21
  • 28

4 Answers4

2

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).

rgettman
  • 167,281
  • 27
  • 248
  • 326
1

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;
    }
  • You still don't get a choice between each iteration. If you type yyyy and hit enter, the loop will repeat 4 times, then the execution (or loop) ends. – F.J Mar 06 '14 at 23:11
0

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
Reimeus
  • 152,723
  • 12
  • 195
  • 261
0

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.

Community
  • 1
  • 1
brindy
  • 3,986
  • 2
  • 20
  • 25