-1

I want to input character from user.If user inputs character 'Y' then continue else exit from application. For looping I am using do-while. Condition for application is used in while block. But it's not working.Whatever user inputs application doesn't exit and continue.

char choice='\u0000';
do
{
    System.out.println("Enter Y to continue or N to exit");
    choice=(char)System.in.read();
}
while(choice!='N');
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Prashant Kumar Sharma
  • 1,120
  • 1
  • 11
  • 21
  • Why u used '\u0000'? – Bacteria Jun 18 '15 at 16:45
  • What character encoding are you reading with the single-byte InputStream `System.in`? – Andy Thomas Jun 18 '15 at 16:46
  • possible duplicate of [How to read a single char from the console in Java (as the user types it)?](http://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) – Tagir Valeev Jun 18 '15 at 16:47
  • To me it seems that your problem is not the *comparing*, but *reading* single character. See the question linked above for some possible solutions. Unfortunately it's not very simple in Java. – Tagir Valeev Jun 18 '15 at 16:48
  • Java's console input is line buffered by default. If you want to respond on each character, it is better to use a library like jline. – Peter Lawrey Jun 18 '15 at 16:48
  • "Whatever user inputs application doesn't exit and continue." Did you try inputting N and pressing enter? – that other guy Jun 18 '15 at 17:22

2 Answers2

0
choice = (char) System.in.read(); 

(casting a byte from system encoding to UTF-16) will only work if the characters have identical values in both encodings; this will usually only work for a very small range of characters. Using Scanner is more reliable.

I updated your query, with Scanner class for reading character.

Scanner reader = new Scanner(System.in);
char choice='\u0000';
do
{
    System.out.println("Enter Y to continue or N to exit");
    choice = reader.next().charAt(0);
}
while(choice!='N' && choice != 'n');
capt.swag
  • 10,335
  • 2
  • 41
  • 41
  • The second line flags "The assigned value never used." It only needs the declaration of `choice`, not the assignment. Also, the case of the response could be more flexible: `while(choice!='N' && choice != 'n');` – rossum Jun 18 '15 at 17:11
0

I think it would be easyer if you do it like this:

char choice='\u0000';
System.out.println("Enter Y to continue or N to exit");
Scanner reader = new Scanner(System.in);
while(choice!='N' && choice!='Y' && choice!='n' && choice!='y') {
    choice = reader.nextLine().charAt(0);
}
reader.close();

After that you can show if he typed N or Y and continue with your code

Nicola Uetz
  • 848
  • 1
  • 7
  • 25